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

  <!-- company_code 필터: SUPER_ADMIN("*")은 전체, 나머지는 자사 데이터만 -->
  <sql id="companyCodeFilter">
    <if test="company_code != null and company_code != &quot;*&quot;">
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
    </if>
  </sql>

  <!-- 페이지네이션: limit/offset 파라미터 기반 -->
  <sql id="pagination">
    <if test="limit != null">
      LIMIT #{limit} OFFSET #{offset}
    </if>
  </sql>

  <!-- 동적 정렬 -->
  <sql id="dynamicOrderBy">
    <choose>
      <when test="sort_column != null and sort_column != ''">
        ORDER BY ${sortColumn}
        <if test="sort_direction != null and sort_direction != ''">
          ${sortDirection}
        </if>
      </when>
      <otherwise>
        ORDER BY CREATED_DATE DESC
      </otherwise>
    </choose>
  </sql>

  <!-- 소프트 삭제 필터 -->
  <sql id="notDeleted">
    AND DELETED_DATE IS NULL
  </sql>

  <!-- 감사 필드 (INSERT용) -->
  <sql id="auditInsertColumns">
    CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE
  </sql>
  <sql id="auditInsertValues">
    #{created_by}, NOW(), #{updated_by}, NOW()
  </sql>

  <!-- 감사 필드 (UPDATE용) -->
  <sql id="auditUpdateSet">
    UPDATED_BY = #{updated_by}, UPDATED_DATE = NOW()
  </sql>

  <!-- 공통 코드 목록 조회 -->
  <select id="selectCodeList" parameterType="map" resultType="map">
    SELECT *
    FROM COMMON_CODE
    WHERE 1=1
    <if test="code_type != null">
      AND CODE_TYPE = #{code_type}
    </if>
    <include refid="companyCodeFilter"/>
    ORDER BY SORT_ORDER ASC
  </select>

  <!-- 동적 테이블 단건 조회 -->
  <select id="selectDynamicOne" parameterType="map" resultType="map">
    SELECT *
    FROM ${tableName}
    WHERE 1=1
    <include refid="companyCodeFilter"/>
    <if test="id != null">
      AND ID = #{id}
    </if>
  </select>

  <!-- 동적 테이블 목록 조회 -->
  <select id="selectDynamicList" parameterType="map" resultType="map">
    SELECT *
    FROM ${tableName}
    WHERE 1=1
    <include refid="companyCodeFilter"/>
    ORDER BY CREATED_DATE DESC
    <include refid="pagination"/>
  </select>

</mapper>
