<?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="entityJoin">

  <!-- ── table_type_columns ─────────────────────────────────────────────── -->

  <!--
    entity/category 타입 컬럼 목록.
    companyCode가 일반 회사 코드이면 해당 회사 + '*' 만 조회 (회사별 설정 우선).
    companyCode가 '*' 이거나 null이면 전체 조회.
  -->
  <select id="selectEntityColumns" parameterType="map" resultType="map">
    SELECT DISTINCT ON (column_name)
      column_name, input_type, reference_table, reference_column, display_column

    FROM table_type_columns

    WHERE table_name = #{table_name}
      AND input_type IN ('entity', 'category')
      AND reference_table IS NOT NULL
      AND reference_table != ''
      <if test="company_code != null and company_code != &quot;&quot; and company_code != &quot;*&quot;">
        AND company_code IN (#{company_code}, '*')
      </if>

    ORDER BY column_name,
      CASE WHEN company_code = '*' THEN 1 ELSE 0 END
  </select>

  <!-- 테이블 컬럼 전체 메타데이터 (display_name, input_type 포함) -->
  <select id="selectColumnMetadata" parameterType="map" resultType="map">
    SELECT DISTINCT ON (column_name)
      column_name, column_label, input_type,
      reference_table, reference_column, display_column, description

    FROM table_type_columns

    WHERE table_name = #{table_name}
      <if test="company_code != null and company_code != &quot;&quot; and company_code != &quot;*&quot;">
        AND company_code IN (#{company_code}, '*')
      </if>

    ORDER BY column_name,
      CASE WHEN company_code = '*' THEN 1 ELSE 0 END
  </select>

  <!--
    Entity 설정 UPSERT.
    Node.js와 동일하게 company_code = '*' 으로 글로벌 레코드를 저장.
    display_column 은 Node.js 원본에 없었으나 이 API 목적상 추가.
  -->
  <insert id="upsertColumnEntitySettings" parameterType="map">
    INSERT INTO table_type_columns (
      table_name, column_name, column_label, input_type,
      reference_table, reference_column, display_column, description,
      display_order, is_visible, is_nullable, company_code,
      created_date, updated_date
    ) VALUES (
      #{table_name}, #{column_name},
      COALESCE(#{column_label}, #{column_name}),
      COALESCE(#{web_type}, 'text'),
      #{reference_table}, #{reference_column},
      #{display_column}, #{description},
      0, TRUE, 'Y', '*',
      NOW(), NOW()
    )
    ON CONFLICT (table_name, column_name, company_code) DO UPDATE SET
      input_type       = COALESCE(EXCLUDED.input_type,       table_type_columns.input_type),
      reference_table  = COALESCE(EXCLUDED.reference_table,  table_type_columns.reference_table),
      reference_column = COALESCE(EXCLUDED.reference_column, table_type_columns.reference_column),
      display_column   = COALESCE(EXCLUDED.display_column,   table_type_columns.display_column),
      column_label     = COALESCE(EXCLUDED.column_label,     table_type_columns.column_label),
      description      = COALESCE(EXCLUDED.description,      table_type_columns.description),
      updated_date     = NOW()
  </insert>

  <!-- ── information_schema ─────────────────────────────────────────────── -->

  <!-- 테이블 존재 여부 -->
  <select id="selectTableExists" parameterType="map" resultType="map">
    SELECT 1 AS exists

    FROM information_schema.tables

    WHERE table_schema = 'public'
      AND table_name   = #{table_name}

    LIMIT 1
  </select>

  <!-- 컬럼 존재 여부 -->
  <select id="selectColumnExists" parameterType="map" resultType="map">
    SELECT 1 AS exists

    FROM information_schema.columns

    WHERE table_schema = 'public'
      AND table_name   = #{table_name}
      AND column_name  = #{column_name}

    LIMIT 1
  </select>

  <!-- 테이블 전체 컬럼 목록 -->
  <select id="selectTableSchemaColumns" parameterType="map" resultType="map">
    SELECT column_name, data_type

    FROM information_schema.columns

    WHERE table_schema = 'public'
      AND table_name   = #{table_name}

    ORDER BY ordinal_position
  </select>

</mapper>
