package com.zioinfo.kintex.livenotice;

import org.apache.ibatis.annotations.Insert;
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-B6) 매퍼.
 * <p>★ Map 반환 @Select 는 camelCase 별칭에 쌍따옴표({@code AS "x"})를 사용한다(PG lower-fold 방지).
 * <p>공개 피드는 status='published' 만, 주최자 목록은 전체.
 */
@Mapper
public interface LiveNoticeMapper {

    @Select("SELECT count(*) FROM event WHERE id = #{eventId}")
    int eventExists(@Param("eventId") String eventId);

    /** 발행. */
    @Insert("""
            INSERT INTO event_live_notice
                (tenant_id, id, event_id, category, title, body, pinned, status, author_name)
            VALUES ('KINTEX', #{id}, #{eventId}, #{category}, #{title}, #{body},
                    #{pinned}, 'published', #{authorName})
            """)
    int insert(Map<String, Object> p);

    /** 단건 조회(테넌트 스코프). */
    @Select("""
            SELECT id, event_id AS "eventId", category, title, body, pinned, status,
                   author_name AS "authorName",
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt",
                   to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "updatedAt"
            FROM event_live_notice
            WHERE tenant_id = 'KINTEX' AND id = #{id}
            """)
    Map<String, Object> findById(@Param("id") String id);

    /** 공개 피드 — 게시 건만. 고정(pinned) 우선, 최신순. */
    @Select("""
            SELECT id, event_id AS "eventId", category, title, body, pinned, status,
                   author_name AS "authorName",
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt",
                   to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "updatedAt"
            FROM event_live_notice
            WHERE tenant_id = 'KINTEX' AND event_id = #{eventId} AND status = 'published'
            ORDER BY pinned DESC, created_at DESC
            LIMIT #{limit}
            """)
    List<Map<String, Object>> findPublicFeed(@Param("eventId") String eventId, @Param("limit") int limit);

    /** 주최자 목록 — 전체 상태(status 필터 선택). */
    @Select("""
            <script>
            SELECT id, event_id AS "eventId", category, title, body, pinned, status,
                   author_name AS "authorName",
                   to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "createdAt",
                   to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "updatedAt"
            FROM event_live_notice
            WHERE tenant_id = 'KINTEX' AND event_id = #{eventId}
            <if test="status != null and status != ''">AND status = #{status}</if>
            ORDER BY pinned DESC, created_at DESC
            LIMIT #{limit}
            </script>
            """)
    List<Map<String, Object>> findForOrganizer(@Param("eventId") String eventId,
                                               @Param("status") String status,
                                               @Param("limit") int limit);

    /** 보관(archive) — 게시 건만 전이. */
    @Update("""
            UPDATE event_live_notice SET status = 'archived', updated_at = now()
            WHERE tenant_id = 'KINTEX' AND id = #{id} AND event_id = #{eventId} AND status = 'published'
            """)
    int archive(@Param("id") String id, @Param("eventId") String eventId);

    /** 고정 토글. */
    @Update("""
            UPDATE event_live_notice SET pinned = #{pinned}, updated_at = now()
            WHERE tenant_id = 'KINTEX' AND id = #{id} AND event_id = #{eventId}
            """)
    int setPinned(@Param("id") String id, @Param("eventId") String eventId, @Param("pinned") boolean pinned);

    /** §5B 알림 팬아웃 대상 — 행사 멤버 user_id 목록(발행 시 in-app 알림). */
    @Select("""
            SELECT DISTINCT user_id AS "userId"
            FROM event_member
            WHERE event_id = #{eventId}
            """)
    List<Map<String, Object>> findEventMemberUserIds(@Param("eventId") String eventId);
}
