package com.zioinfo.kintex.document;

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;

/**
 * M6 서류·마일스톤 매퍼 — event_milestone·required_document·document_review_issue read + 상태 전이 update.
 * camelCase 별칭은 반드시 쌍따옴표(PG 소문자 폴딩 함정) — WORK_STATUS §7.
 */
@Mapper
public interface DocumentMapper {

    /** 행사 마일스톤(정렬 순). */
    @Select("""
            SELECT label,
                   state,
                   to_char(due_date, 'YYYY-MM-DD') AS "dueDate",
                   sort_order AS "sortOrder"
            FROM event_milestone
            WHERE event_id = #{eventId}
            ORDER BY sort_order, due_date NULLS LAST
            """)
    List<Map<String, Object>> findMilestones(@Param("eventId") String eventId);

    /** 신고서류 체크리스트(정렬 순). */
    @Select("""
            SELECT doc_type AS "docType",
                   name,
                   status,
                   to_char(due_date, 'YYYY-MM-DD') AS "dueDate",
                   sort_order AS "sortOrder"
            FROM required_document
            WHERE event_id = #{eventId}
            ORDER BY sort_order, doc_type
            """)
    List<Map<String, Object>> findDocuments(@Param("eventId") String eventId);

    /** 단일 서류(상태 전이 대상 존재 확인). 없으면 null. */
    @Select("""
            SELECT doc_type AS "docType",
                   name,
                   status,
                   to_char(due_date, 'YYYY-MM-DD') AS "dueDate",
                   sort_order AS "sortOrder"
            FROM required_document
            WHERE event_id = #{eventId} AND doc_type = #{docType}
            """)
    Map<String, Object> findDocument(@Param("eventId") String eventId, @Param("docType") String docType);

    /** AI 검수 이슈(정렬 순). */
    @Select("""
            SELECT tone, title, description, sort_order AS "sortOrder"
            FROM document_review_issue
            WHERE event_id = #{eventId}
            ORDER BY sort_order, id
            """)
    List<Map<String, Object>> findReviewIssues(@Param("eventId") String eventId);

    /** 서류 상태 전이(임시저장/제출). 영향 행수 반환. */
    @Update("""
            UPDATE required_document
            SET status = #{status}, updated_at = now()
            WHERE event_id = #{eventId} AND doc_type = #{docType}
            """)
    int updateStatus(@Param("eventId") String eventId,
                     @Param("docType") String docType,
                     @Param("status") String status);
}
