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

  <!--
    external_db_connections 테이블 CRUD
    map-underscore-to-camel-case: true → 컬럼 snake_case → Map 키 camelCase 자동 변환
    connection_options: JSONB → ::TEXT 캐스트 후 서비스에서 파싱
  -->

  <!-- 목록 조회 (비밀번호 마스킹, company_mng JOIN) -->
  <select id="getExternalDbConnectionList" parameterType="map" resultType="map">
    SELECT
        E.ID
        , E.CONNECTION_NAME
        , E.DESCRIPTION
        , E.DB_TYPE
        , E.HOST
        , E.PORT
        , E.DATABASE_NAME
        , E.USERNAME
        , '***ENCRYPTED***'                  AS PASSWORD
        , E.CONNECTION_TIMEOUT
        , E.QUERY_TIMEOUT
        , E.MAX_CONNECTIONS
        , E.SSL_ENABLED
        , E.SSL_CERT_PATH
        , E.CONNECTION_OPTIONS::TEXT          AS CONNECTION_OPTIONS
        , E.COMPANY_CODE
        , E.IS_ACTIVE
        , E.CREATED_BY
        , E.UPDATED_BY
        , E.CREATED_DATE
        , E.UPDATED_DATE
        , COALESCE(C.COMPANY_NAME,
            CASE WHEN E.COMPANY_CODE = '*' THEN '전체' ELSE E.COMPANY_CODE END
          )                                   AS COMPANY_NAME
    FROM EXTERNAL_DB_CONNECTIONS E
    LEFT JOIN COMPANY_MNG C
        ON E.COMPANY_CODE = C.COMPANY_CODE
    <where>
      <if test="filter_company_code != null and filter_company_code != &quot;*&quot;">
        AND (E.COMPANY_CODE = #{filter_company_code} OR E.COMPANY_CODE = '*')
      </if>
      <if test="db_type != null and db_type != ''">
        AND E.DB_TYPE = #{db_type}
      </if>
      <if test="is_active != null and is_active != ''">
        AND E.IS_ACTIVE = #{is_active}
      </if>
      <if test="search != null and search != ''">
        AND (E.CONNECTION_NAME ILIKE #{search} OR E.DESCRIPTION ILIKE #{search})
      </if>
    </where>
    ORDER BY E.IS_ACTIVE DESC, E.CONNECTION_NAME ASC
  </select>

  <!-- 단건 조회 (비밀번호 마스킹) -->
  <select id="getExternalDbConnectionInfo" parameterType="map" resultType="map">
    SELECT
        E.ID
        , E.CONNECTION_NAME
        , E.DESCRIPTION
        , E.DB_TYPE
        , E.HOST
        , E.PORT
        , E.DATABASE_NAME
        , E.USERNAME
        , '***ENCRYPTED***'          AS PASSWORD
        , E.CONNECTION_TIMEOUT
        , E.QUERY_TIMEOUT
        , E.MAX_CONNECTIONS
        , E.SSL_ENABLED
        , E.SSL_CERT_PATH
        , E.CONNECTION_OPTIONS::TEXT AS CONNECTION_OPTIONS
        , E.COMPANY_CODE
        , E.IS_ACTIVE
        , E.CREATED_BY
        , E.UPDATED_BY
        , E.CREATED_DATE
        , E.UPDATED_DATE
    FROM EXTERNAL_DB_CONNECTIONS E
    WHERE E.ID = #{id}::varchar
  </select>

  <!-- 단건 조회 (비밀번호 포함 - 내부 전용) -->
  <select id="getExternalDbConnectionInfoWithPassword" parameterType="map" resultType="map">
    SELECT
        ID
        , CONNECTION_NAME
        , DESCRIPTION
        , DB_TYPE
        , HOST
        , PORT
        , DATABASE_NAME
        , USERNAME
        , PASSWORD
        , CONNECTION_TIMEOUT
        , QUERY_TIMEOUT
        , MAX_CONNECTIONS
        , SSL_ENABLED
        , SSL_CERT_PATH
        , CONNECTION_OPTIONS::TEXT AS CONNECTION_OPTIONS
        , COMPANY_CODE
        , IS_ACTIVE
        , CREATED_BY
        , UPDATED_BY
        , CREATED_DATE
        , UPDATED_DATE
    FROM EXTERNAL_DB_CONNECTIONS
    WHERE ID = #{id}::varchar
  </select>

  <!-- 비밀번호만 조회 -->
  <select id="getExternalDbConnectionPassword" parameterType="map" resultType="map">
    SELECT PASSWORD
    FROM EXTERNAL_DB_CONNECTIONS
    WHERE ID = #{id}::varchar
  </select>

  <!-- 이름+회사 중복 확인 -->
  <select id="getExternalDbConnectionByName" parameterType="map" resultType="map">
    SELECT ID
    FROM EXTERNAL_DB_CONNECTIONS
    WHERE CONNECTION_NAME = #{connection_name}
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
    LIMIT 1
  </select>

  <!-- 이름+회사 중복 확인 (자신 제외) -->
  <select id="getExternalDbConnectionByNameExclude" parameterType="map" resultType="map">
    SELECT ID
    FROM EXTERNAL_DB_CONNECTIONS
    WHERE CONNECTION_NAME = #{connection_name}
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
      AND ID != #{exclude_id}::varchar
    LIMIT 1
  </select>

  <!-- 생성 -->
  <insert id="insertExternalDbConnection" parameterType="map" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    INSERT INTO EXTERNAL_DB_CONNECTIONS (
        CONNECTION_NAME
        , DESCRIPTION
        , DB_TYPE
        , HOST
        , PORT
        , DATABASE_NAME
        , USERNAME
        , PASSWORD
        , CONNECTION_TIMEOUT
        , QUERY_TIMEOUT
        , MAX_CONNECTIONS
        , SSL_ENABLED
        , SSL_CERT_PATH
        , CONNECTION_OPTIONS
        , COMPANY_CODE
        , IS_ACTIVE
        , CREATED_BY
        , UPDATED_BY
        , CREATED_DATE
        , UPDATED_DATE
    ) VALUES (
        #{connection_name}
        , #{description}
        , #{db_type}
        , #{host}
        , #{port}::varchar
        , #{database_name}
        , #{username}
        , #{password}
        , #{connection_timeout}::varchar
        , #{query_timeout}::varchar
        , #{max_connections}::varchar
        , #{ssl_enabled}
        , #{ssl_cert_path}
        , #{connection_options}::JSONB
        , #{company_code}
        , #{is_active}
        , #{created_by}
        , #{updated_by}
        , NOW()
        , NOW()
    )
  </insert>

  <!-- 수정 (동적 UPDATE) -->
  <update id="updateExternalDbConnection" parameterType="map">
    UPDATE EXTERNAL_DB_CONNECTIONS
    <set>
      <if test="connection_name != null">CONNECTION_NAME = #{connection_name},</if>
      <if test="description != null">DESCRIPTION = #{description},</if>
      <if test="db_type != null">DB_TYPE = #{db_type},</if>
      <if test="host != null">HOST = #{host},</if>
      <if test="port != null">PORT = #{port}::varchar,</if>
      <if test="database_name != null">DATABASE_NAME = #{database_name},</if>
      <if test="username != null">USERNAME = #{username},</if>
      <if test="password != null">PASSWORD = #{password},</if>
      <if test="connection_timeout != null">CONNECTION_TIMEOUT = #{connection_timeout}::varchar,</if>
      <if test="query_timeout != null">QUERY_TIMEOUT = #{query_timeout}::varchar,</if>
      <if test="max_connections != null">MAX_CONNECTIONS = #{max_connections}::varchar,</if>
      <if test="ssl_enabled != null">SSL_ENABLED = #{ssl_enabled},</if>
      <if test="ssl_cert_path != null">SSL_CERT_PATH = #{ssl_cert_path},</if>
      <if test="connection_options != null">CONNECTION_OPTIONS = #{connection_options}::JSONB,</if>
      <if test="company_code != null">COMPANY_CODE = #{company_code},</if>
      <if test="is_active != null">IS_ACTIVE = #{is_active},</if>
      <if test="updated_by != null">UPDATED_BY = #{updated_by},</if>
      UPDATED_DATE = NOW()
    </set>
    WHERE ID = #{id}::varchar
  </update>

  <!-- 삭제 -->
  <delete id="deleteExternalDbConnection" parameterType="map">
    DELETE FROM EXTERNAL_DB_CONNECTIONS
    WHERE ID = #{id}::varchar
    <if test="company_code != null and company_code != &quot;*&quot;">
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
    </if>
  </delete>

  <!-- DB 타입 카테고리 목록 -->
  <select id="getExternalDbTypeCategories" resultType="map">
    SELECT
        TYPE_CODE
        , DISPLAY_NAME
        , ICON
        , COLOR
        , SORT_ORDER
    FROM DB_TYPE_CATEGORIES
    WHERE IS_ACTIVE = TRUE
    ORDER BY SORT_ORDER ASC, DISPLAY_NAME ASC
  </select>

</mapper>
