<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="entityReference">

  <!-- 컬럼 메타 정보 조회 (company_code='*' 고정) -->
  <select id="selectColumnInfo" parameterType="map" resultType="map">
    SELECT
      input_type       AS input_type,
      reference_table  AS reference_table,
      reference_column AS reference_column,
      display_column   AS display_column

    FROM table_type_columns

    WHERE table_name  = #{table_name}
      AND column_name = #{column_name}
      AND company_code = '*'

    LIMIT 1
  </select>

  <!-- 테이블 존재 여부 (information_schema) -->
  <select id="checkTableExistsInSchema" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM information_schema.tables

    WHERE table_schema = 'public'
      AND table_name   = #{table_name}
  </select>

  <!-- company_code 컬럼 존재 여부 -->
  <select id="checkTableHasCompanyCode" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM information_schema.columns

    WHERE table_schema = 'public'
      AND table_name   = #{table_name}
      AND column_name  = 'company_code'
  </select>

  <!--
    동적 참조 테이블 조회.
    tableName, referenceColumn, displayColumn 은 Java에서 [a-zA-Z0-9_] 로 sanitize 후 전달.
    companyCode 필터는 hasCompanyCode=true 일 때만 적용.
  -->
  <select id="selectReferenceData" parameterType="map" resultType="map">
    SELECT ${referenceColumn} AS ref_value,
           ${displayColumn}   AS display_name

    FROM ${tableName}
    <where>
      <if test='has_company_code and company_code != null and company_code != "*"'>
        (company_code = #{company_code} OR company_code = '*')
      </if>
      <if test="search_like != null">
        AND ${displayColumn} ILIKE #{search_like}
      </if>
    </where>

    ORDER BY ${displayColumn}
    LIMIT #{limit}
  </select>

  <!-- 공통 코드 조회 -->
  <select id="selectCodeData" parameterType="map" resultType="map">
    SELECT code_value AS code_value, code_name AS code_name

    FROM code_info

    WHERE code_info = #{code_info}
      AND is_active     = 'Y'
    <if test='company_code != null and company_code != "*"'>
      AND (company_code = #{company_code} OR company_code = '*')
    </if>
    <if test="search_like != null">
      AND code_name ILIKE #{search_like}
    </if>

    ORDER BY code_name ASC
    LIMIT #{limit}
  </select>

</mapper>
