package com.zioinfo.kintex.system.rolemenu;

import org.apache.ibatis.annotations.*;

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

/** 역할-메뉴 매핑 매퍼(sys_role_menu). 전역 규약(sys_menu·sys_role 참조). */
@Mapper
public interface RoleMenuMapper {

    /** 전체 메뉴 + 해당 역할의 매핑 상태(LEFT JOIN). */
    @Select("SELECT m.id AS \"menuId\", m.menu_name AS \"menuName\", m.parent_id AS \"parentId\", "
            + "m.sort_order AS \"sortOrder\", "
            + "(rm.menu_id IS NOT NULL) AS \"mapped\", "
            + "COALESCE(rm.read_yn,'N') AS \"readYn\", COALESCE(rm.write_yn,'N') AS \"writeYn\" "
            + "FROM sys_menu m "
            + "LEFT JOIN sys_role_menu rm ON rm.menu_id = m.id AND rm.role_code = #{roleCode} "
            + "ORDER BY m.sort_order, m.id")
    List<Map<String, Object>> findByRole(@Param("roleCode") String roleCode);

    @Delete("DELETE FROM sys_role_menu WHERE role_code = #{roleCode}")
    int clear(@Param("roleCode") String roleCode);

    @Insert("INSERT INTO sys_role_menu (role_code, menu_id, read_yn, write_yn) "
            + "VALUES (#{roleCode}, #{menuId}, COALESCE(#{readYn},'Y'), COALESCE(#{writeYn},'N')) "
            + "ON CONFLICT (role_code, menu_id) DO UPDATE SET read_yn=EXCLUDED.read_yn, write_yn=EXCLUDED.write_yn")
    int add(@Param("roleCode") String roleCode, @Param("menuId") String menuId,
            @Param("readYn") String readYn, @Param("writeYn") String writeYn);

    @Select("SELECT COUNT(*) FROM sys_role WHERE role_code = #{roleCode}")
    int roleExists(@Param("roleCode") String roleCode);
}
