package com.zioinfo.kintex.system.holiday;

import org.apache.ibatis.annotations.*;

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

/**
 * 공휴일 매퍼 — V41 holiday 테이블(PK tenant_id, ymd) 조회·관리.
 * 정렬 권위 = ymd ASC. ymd는 to_char로 yyyy-MM-dd 문자열 반환(프론트 셀 매칭 키).
 * ★MyBatis 어노테이션 규약: 별칭 AS "x" 쌍따옴표, {@code <script>}/`<` 미사용(MapperAnnotationParseTest).
 */
@Mapper
public interface HolidayMapper {

    String COLS = "to_char(ymd, 'YYYY-MM-DD') AS ymd, name, "
            + "is_substitute AS \"isSubstitute\", is_holiday AS \"isHoliday\"";

    /** 관리자 — 기간 내 전체(휴무 off 포함), 날짜 오름차순. */
    @Select("SELECT " + COLS + " FROM holiday "
            + "WHERE tenant_id = #{tenantId} AND ymd BETWEEN CAST(#{fromYmd} AS date) AND CAST(#{toYmd} AS date) "
            + "ORDER BY ymd")
    List<Map<String, Object>> findRange(@Param("tenantId") String tenantId,
                                        @Param("fromYmd") String fromYmd,
                                        @Param("toYmd") String toYmd);

    /** 공개(인증) — 기간 내 실제 휴무(is_holiday = true)만, 날짜 오름차순. 캘린더 붉은색 표시용. */
    @Select("SELECT " + COLS + " FROM holiday "
            + "WHERE tenant_id = #{tenantId} AND is_holiday = true "
            + "AND ymd BETWEEN CAST(#{fromYmd} AS date) AND CAST(#{toYmd} AS date) "
            + "ORDER BY ymd")
    List<Map<String, Object>> findActiveRange(@Param("tenantId") String tenantId,
                                              @Param("fromYmd") String fromYmd,
                                              @Param("toYmd") String toYmd);

    /** 존재 확인(중복 추가 방지). */
    @Select("SELECT COUNT(1) FROM holiday WHERE tenant_id = #{tenantId} AND ymd = CAST(#{ymd} AS date)")
    int exists(@Param("tenantId") String tenantId, @Param("ymd") String ymd);

    /** 임시공휴일 추가(등록 즉시 휴무). PK 충돌은 서비스에서 사전 차단(409). */
    @Insert("INSERT INTO holiday (tenant_id, ymd, name, is_substitute, is_holiday) "
            + "VALUES (#{tenantId}, CAST(#{ymd} AS date), #{name}, COALESCE(#{isSubstitute}, false), true)")
    int insert(@Param("tenantId") String tenantId, @Param("ymd") String ymd,
               @Param("name") String name, @Param("isSubstitute") Boolean isSubstitute);

    /** 삭제. */
    @Delete("DELETE FROM holiday WHERE tenant_id = #{tenantId} AND ymd = CAST(#{ymd} AS date)")
    int delete(@Param("tenantId") String tenantId, @Param("ymd") String ymd);

    /** 휴무 여부 토글(임시휴무 on/off). */
    @Update("UPDATE holiday SET is_holiday = #{isHoliday} "
            + "WHERE tenant_id = #{tenantId} AND ymd = CAST(#{ymd} AS date)")
    int updateHoliday(@Param("tenantId") String tenantId, @Param("ymd") String ymd,
                      @Param("isHoliday") boolean isHoliday);

    /** 연도 목록(년 선택 드롭다운) — 데이터 존재 연도 내림차순. */
    @Select("SELECT DISTINCT EXTRACT(YEAR FROM ymd)::int AS y FROM holiday "
            + "WHERE tenant_id = #{tenantId} ORDER BY y DESC")
    List<Integer> findYears(@Param("tenantId") String tenantId);
}
