package com.zioinfo.kintex.system.dept;

import org.apache.ibatis.annotations.*;

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

/** 부서 매퍼(dept). 테넌트 스코프(V31 표준). */
@Mapper
public interface DeptMapper {

    @Select("SELECT id, dept_name AS \"deptName\", parent_id AS \"parentId\", "
            + "sort_order AS \"sortOrder\", use_yn AS \"useYn\" "
            + "FROM dept WHERE tenant_id = #{tenantId} ORDER BY sort_order, id")
    List<Map<String, Object>> findAll(@Param("tenantId") String tenantId);

    @Insert("INSERT INTO dept (tenant_id, id, dept_name, parent_id, sort_order, use_yn) "
            + "VALUES (#{tenantId}, #{id}, #{deptName}, #{parentId}, COALESCE(#{sortOrder},0), COALESCE(#{useYn},'Y')) "
            + "ON CONFLICT (tenant_id, id) DO UPDATE SET dept_name=EXCLUDED.dept_name, parent_id=EXCLUDED.parent_id, "
            + "sort_order=EXCLUDED.sort_order, use_yn=EXCLUDED.use_yn, updated_at=now()")
    int upsert(Map<String, Object> p);

    @Delete("DELETE FROM dept WHERE tenant_id = #{tenantId} AND id = #{id}")
    int delete(@Param("tenantId") String tenantId, @Param("id") String id);

    @Select("SELECT count(*) FROM dept WHERE tenant_id = #{tenantId} AND parent_id = #{id}")
    int countChildren(@Param("tenantId") String tenantId, @Param("id") String id);
}
