package com.zioinfo.kintex.system.commoncode;

import org.apache.ibatis.annotations.*;

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

/** 공통코드 그룹/값 매퍼(TB_CODE_GRP/TB_CODE 이식). */
@Mapper
public interface CommonCodeMapper {

    @Select("SELECT grp_code AS \"grpCode\", grp_name AS \"grpName\", description, use_yn AS \"useYn\", "
            + "sort_order AS \"sortOrder\" FROM common_code_group ORDER BY sort_order, grp_code")
    List<Map<String, Object>> findGroups();

    @Select("SELECT grp_code AS \"grpCode\", code, code_name AS \"codeName\", code_value AS \"codeValue\", "
            + "sort_order AS \"sortOrder\", use_yn AS \"useYn\", attr1 FROM common_code "
            + "WHERE grp_code = #{grpCode} AND use_yn = 'Y' ORDER BY sort_order, code")
    List<Map<String, Object>> findCodes(@Param("grpCode") String grpCode);

    @Insert("INSERT INTO common_code_group (grp_code, grp_name, description, use_yn, sort_order) "
            + "VALUES (#{grpCode}, #{grpName}, #{description}, COALESCE(#{useYn},'Y'), COALESCE(#{sortOrder},0)) "
            + "ON CONFLICT (grp_code) DO UPDATE SET grp_name=EXCLUDED.grp_name, "
            + "description=EXCLUDED.description, use_yn=EXCLUDED.use_yn, sort_order=EXCLUDED.sort_order, "
            + "updated_at=now()")
    int upsertGroup(Map<String, Object> p);

    @Delete("DELETE FROM common_code_group WHERE grp_code = #{grpCode}")
    int deleteGroup(@Param("grpCode") String grpCode);

    @Insert("INSERT INTO common_code (grp_code, code, code_name, code_value, sort_order, use_yn, attr1) "
            + "VALUES (#{grpCode}, #{code}, #{codeName}, #{codeValue}, COALESCE(#{sortOrder},0), "
            + "COALESCE(#{useYn},'Y'), #{attr1}) "
            + "ON CONFLICT (grp_code, code) DO UPDATE SET code_name=EXCLUDED.code_name, "
            + "code_value=EXCLUDED.code_value, sort_order=EXCLUDED.sort_order, use_yn=EXCLUDED.use_yn, "
            + "attr1=EXCLUDED.attr1, updated_at=now()")
    int upsertCode(Map<String, Object> p);

    @Delete("DELETE FROM common_code WHERE grp_code = #{grpCode} AND code = #{code}")
    int deleteCode(@Param("grpCode") String grpCode, @Param("code") String code);
}
