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

  <!-- 공통 SELECT 컬럼 (jsonb → text cast) -->
  <sql id="selectColumns">
    E.ID
    , E.CONNECTION_NAME
    , E.DESCRIPTION
    , E.BASE_URL
    , E.ENDPOINT_PATH
    , E.DEFAULT_HEADERS::TEXT AS DEFAULT_HEADERS
    , E.DEFAULT_METHOD
    , E.DEFAULT_REQUEST_BODY AS DEFAULT_BODY
    , E.AUTH_TYPE
    , E.AUTH_CONFIG::TEXT AS AUTH_CONFIG
    , E.TIMEOUT
    , E.RETRY_COUNT
    , E.RETRY_DELAY
    , E.COMPANY_CODE
    , E.IS_ACTIVE
    , E.CREATED_DATE
    , E.CREATED_BY
    , E.UPDATED_DATE
    , E.UPDATED_BY
    , E.LAST_TEST_DATE
    , E.LAST_TEST_RESULT
    , E.LAST_TEST_MESSAGE
    , E.SAVE_TO_HISTORY
  </sql>

  <!-- 연결 목록 조회 -->
  <select id="getExternalRestApiConnectionList" parameterType="map" resultType="map">
    SELECT
        <include refid="selectColumns"/>
        , COALESCE(C.COMPANY_NAME,
            CASE WHEN E.COMPANY_CODE = '*' THEN '전체' ELSE E.COMPANY_CODE END
          ) AS COMPANY_NAME
    FROM EXTERNAL_REST_API_CONNECTIONS E
    LEFT JOIN COMPANY_MNG C
        ON E.COMPANY_CODE = C.COMPANY_CODE
    WHERE 1=1
    <!-- inline company_code filter: CommonMapper.companyCodeFilter 사용 불가 (JOIN 시 컬럼명 ambiguous) -->
    <if test='company_code != null and company_code != "*"'>
      AND (E.COMPANY_CODE = #{company_code} OR E.COMPANY_CODE = '*')
    </if>
    <if test='company_code == "*" and filter_company_code != null and filter_company_code != ""'>
      AND (E.COMPANY_CODE = #{filter_company_code} OR E.COMPANY_CODE = '*')
    </if>
    <if test="is_active != null and is_active != ''">
      AND E.IS_ACTIVE = #{is_active}
    </if>
    <if test="auth_type != null and auth_type != ''">
      AND E.AUTH_TYPE = #{auth_type}
    </if>
    <if test="search != null and search != ''">
      AND (
        E.CONNECTION_NAME ILIKE #{search}
        OR E.DESCRIPTION ILIKE #{search}
        OR E.BASE_URL ILIKE #{search}
      )
    </if>
    ORDER BY E.CREATED_DATE DESC
  </select>

  <!-- 연결 상세 조회 -->
  <select id="getExternalRestApiConnectionInfo" parameterType="map" resultType="map">
    SELECT
        <include refid="selectColumns"/>
    FROM EXTERNAL_REST_API_CONNECTIONS E
    WHERE E.ID = #{id}::varchar
    <include refid="common.companyCodeFilter"/>
  </select>

  <!-- 연결 생성 -->
  <insert id="insertExternalRestApiConnection" parameterType="map" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    INSERT INTO EXTERNAL_REST_API_CONNECTIONS (
        CONNECTION_NAME
        , DESCRIPTION
        , BASE_URL
        , ENDPOINT_PATH
        , DEFAULT_HEADERS
        , DEFAULT_METHOD
        , DEFAULT_REQUEST_BODY
        , AUTH_TYPE
        , AUTH_CONFIG
        , TIMEOUT
        , RETRY_COUNT
        , RETRY_DELAY
        , COMPANY_CODE
        , IS_ACTIVE
        , CREATED_BY
        , SAVE_TO_HISTORY
    ) VALUES (
        #{connection_name}
        , #{description}
        , #{base_url}
        , #{endpoint_path}
        , #{default_headers,jdbcType=OTHER}::JSONB
        , #{default_method}
        , #{default_body}
        , #{auth_type}
        , #{auth_config,jdbcType=OTHER}::JSONB
        , #{timeout}
        , #{retry_count}
        , #{retry_delay}
        , #{company_code}
        , #{is_active}
        , #{created_by}
        , #{save_to_history}
    )
  </insert>

  <!-- 연결 수정 -->
  <update id="updateExternalRestApiConnection" parameterType="map">
    UPDATE EXTERNAL_REST_API_CONNECTIONS
    <set>
      UPDATED_DATE = NOW(),
      <if test="connection_name != null">CONNECTION_NAME = #{connection_name},</if>
      <if test="description != null">DESCRIPTION = #{description},</if>
      <if test="base_url != null">BASE_URL = #{base_url},</if>
      <if test="endpoint_path != null">ENDPOINT_PATH = #{endpoint_path},</if>
      <if test="default_headers != null">DEFAULT_HEADERS = #{default_headers,jdbcType=OTHER}::JSONB,</if>
      <if test="default_method != null">DEFAULT_METHOD = #{default_method},</if>
      <if test="has_default_body != null">DEFAULT_REQUEST_BODY = #{default_body},</if>
      <if test="auth_type != null">AUTH_TYPE = #{auth_type},</if>
      <if test="auth_config != null">AUTH_CONFIG = #{auth_config,jdbcType=OTHER}::JSONB,</if>
      <if test="timeout != null">TIMEOUT = #{timeout},</if>
      <if test="retry_count != null">RETRY_COUNT = #{retry_count},</if>
      <if test="retry_delay != null">RETRY_DELAY = #{retry_delay},</if>
      <if test="is_active != null">IS_ACTIVE = #{is_active},</if>
      <if test="save_to_history != null">SAVE_TO_HISTORY = #{save_to_history},</if>
      <if test="updated_by != null">UPDATED_BY = #{updated_by},</if>
    </set>
    WHERE ID = #{id}::varchar
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- 연결 삭제 -->
  <delete id="deleteExternalRestApiConnection" parameterType="map">
    DELETE FROM EXTERNAL_REST_API_CONNECTIONS
    WHERE ID = #{id}::varchar
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- 테스트 결과 업데이트 -->
  <update id="updateExternalRestApiConnectionTestResult" parameterType="map">
    UPDATE EXTERNAL_REST_API_CONNECTIONS
    SET
        LAST_TEST_DATE = NOW()
        , LAST_TEST_RESULT = #{last_test_result}
        , LAST_TEST_MESSAGE = #{last_test_message}
    WHERE ID = #{id}::varchar
  </update>

  <!-- DB 토큰 조회 (db-token auth type) -->
  <!-- 주의: tableName, columnName, whereColumn은 서비스에서 정규식 검증 후 전달 -->
  <select id="getExternalRestApiConnectionDbToken" parameterType="map" resultType="map">
    SELECT ${valueColumn} AS TOKEN_VALUE
    FROM ${tableName}
    WHERE (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
    <if test="where_column != null and where_value != null">
      AND ${whereColumn} = #{where_value}
    </if>
    ORDER BY UPDATED_DATE DESC
    LIMIT 1
  </select>

</mapper>
