package com.zioinfo.kintex.visitor.feed;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * F-C7 최근 본 행사·부스 피드 매퍼. tenant_id='KINTEX' 고정. 본인(user_id)만.
 */
@Mapper
public interface FeedMapper {

    /** 조회 이력 upsert — 동일 (user,item) 재조회는 viewed_at·제목 갱신. */
    @Update("""
            INSERT INTO visitor_view_history
                (tenant_id, id, user_id, item_type, item_id, item_title, item_sub, viewed_at)
            VALUES
                ('KINTEX', #{id}, #{userId}, #{itemType}, #{itemId}, #{itemTitle}, #{itemSub}, now())
            ON CONFLICT (user_id, item_type, item_id)
            DO UPDATE SET item_title = EXCLUDED.item_title,
                          item_sub   = EXCLUDED.item_sub,
                          viewed_at  = now()
            """)
    void upsertView(Map<String, Object> row);

    /** 최근 본 목록. */
    @Select("""
            SELECT id,
                   item_type  AS "itemType",
                   item_id    AS "itemId",
                   item_title AS "itemTitle",
                   item_sub   AS "itemSub",
                   to_char(viewed_at, 'YYYY-MM-DD"T"HH24:MI:SS') AS "viewedAt"
            FROM visitor_view_history
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
            ORDER BY viewed_at DESC
            LIMIT #{limit}
            """)
    List<Map<String, Object>> listRecent(@Param("userId") String userId, @Param("limit") int limit);

    /** 상한 초과분 정리(최근 200건 유지). */
    @Delete("""
            DELETE FROM visitor_view_history
            WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
              AND id NOT IN (
                SELECT id FROM visitor_view_history
                WHERE tenant_id = 'KINTEX' AND user_id = #{userId}
                ORDER BY viewed_at DESC
                LIMIT 200
              )
            """)
    void prune(@Param("userId") String userId);
}
