package com.zioinfo.kintex.system.message;

import org.apache.ibatis.annotations.*;

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

/**
 * 메시지 템플릿 매퍼(sys_message). 필터는 null-safe(값이 없으면 조건 무시) — &lt;script&gt; 미사용.
 * <p>클래스명 Sys* 접두 — 기존 {@code work.message.MessageMapper} 와 MyBatis 매퍼 빈명 충돌 회피.
 */
@Mapper
public interface SysMessageMapper {

    @Select("SELECT msg_code AS \"msgCode\", locale, category, title, template, use_yn AS \"useYn\", "
            + "to_char(updated_at,'YYYY-MM-DD\"T\"HH24:MI:SS') AS \"updatedAt\" FROM sys_message "
            + "WHERE tenant_id = #{tenantId} "
            + "AND (#{category} IS NULL OR category = #{category}) "
            + "AND (#{locale} IS NULL OR locale = #{locale}) "
            + "ORDER BY category, msg_code, locale")
    List<Map<String, Object>> findAll(@Param("tenantId") String tenantId,
                                      @Param("category") String category,
                                      @Param("locale") String locale);

    /** 코드로 로케일 목록 조회(관리 상세). */
    @Select("SELECT msg_code AS \"msgCode\", locale, category, title, template, use_yn AS \"useYn\", "
            + "to_char(updated_at,'YYYY-MM-DD\"T\"HH24:MI:SS') AS \"updatedAt\" FROM sys_message "
            + "WHERE tenant_id = #{tenantId} AND msg_code = #{msgCode} ORDER BY locale")
    List<Map<String, Object>> findByCode(@Param("tenantId") String tenantId,
                                         @Param("msgCode") String msgCode);

    /** 렌더용 단건 조회 — 정확 로케일 우선, 없으면 ko 폴백은 서비스에서 처리. */
    @Select("SELECT msg_code AS \"msgCode\", locale, category, title, template, use_yn AS \"useYn\" "
            + "FROM sys_message WHERE tenant_id = #{tenantId} AND msg_code = #{msgCode} "
            + "AND locale = #{locale} AND use_yn = 'Y'")
    Map<String, Object> findOne(@Param("tenantId") String tenantId,
                                @Param("msgCode") String msgCode,
                                @Param("locale") String locale);

    @Insert("INSERT INTO sys_message (tenant_id, msg_code, locale, category, title, template, use_yn) "
            + "VALUES (#{tenantId}, #{msgCode}, COALESCE(#{locale},'ko'), #{category}, #{title}, #{template}, "
            + "COALESCE(#{useYn},'Y')) "
            + "ON CONFLICT (tenant_id, msg_code, locale) DO UPDATE SET category=EXCLUDED.category, "
            + "title=EXCLUDED.title, template=EXCLUDED.template, use_yn=EXCLUDED.use_yn, updated_at=now()")
    int upsert(Map<String, Object> p);

    @Delete("DELETE FROM sys_message WHERE tenant_id = #{tenantId} AND msg_code = #{msgCode} "
            + "AND (#{locale} IS NULL OR locale = #{locale})")
    int delete(@Param("tenantId") String tenantId,
               @Param("msgCode") String msgCode,
               @Param("locale") String locale);
}
