package com.zioinfo.kintex.system.role;

import org.apache.ibatis.annotations.*;

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

/** 역할/권한 매퍼(RBAC 확장). */
@Mapper
public interface RoleMapper {

    @Select("SELECT role_code AS \"roleCode\", role_name AS \"roleName\", description, use_yn AS \"useYn\" "
            + "FROM sys_role ORDER BY role_code")
    List<Map<String, Object>> findRoles();

    @Select("SELECT perm_code AS \"permCode\", perm_name AS \"permName\", description "
            + "FROM sys_permission ORDER BY perm_code")
    List<Map<String, Object>> findPermissions();

    @Select("SELECT perm_code FROM sys_role_permission WHERE role_code = #{roleCode} ORDER BY perm_code")
    List<String> findRolePermissions(@Param("roleCode") String roleCode);

    @Insert("INSERT INTO sys_role (role_code, role_name, description, use_yn) "
            + "VALUES (#{roleCode}, #{roleName}, #{description}, COALESCE(#{useYn},'Y')) "
            + "ON CONFLICT (role_code) DO UPDATE SET role_name=EXCLUDED.role_name, "
            + "description=EXCLUDED.description, use_yn=EXCLUDED.use_yn")
    int upsertRole(Map<String, Object> p);

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

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

    @Insert("INSERT INTO sys_role_permission (role_code, perm_code) VALUES (#{roleCode}, #{permCode}) "
            + "ON CONFLICT DO NOTHING")
    int addRolePermission(@Param("roleCode") String roleCode, @Param("permCode") String permCode);
}
