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

  <!--
    LAYOUT_STANDARDS 공통 WHERE 절
    - IS_ACTIVE = 'Y' 필수
    - includePublic=true  → (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*') OR IS_PUBLIC = 'Y'
    - includePublic=false → (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*') 만
    - 검색: CATEGORY / LAYOUT_TYPE / SEARCH_TERM 옵션
    ※ CompanyCodeFilter 공통 fragment 대신 커스텀 SQL 사용:
      IS_PUBLIC 조건이 추가되므로 CommonMapper.companyCodeFilter 와 로직이 다름.
  -->
  <sql id="layoutWhereClause">
    WHERE IS_ACTIVE = 'Y'
    <choose>
      <when test="include_public == true">
        AND ((COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*') OR IS_PUBLIC = 'Y')
      </when>
      <otherwise>
        AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
      </otherwise>
    </choose>
    <if test="category != null and category != ''">
      AND CATEGORY = #{category}
    </if>
    <if test="layout_type != null and layout_type != ''">
      AND LAYOUT_TYPE = #{layout_type}
    </if>
    <if test="search_term != null and search_term != ''">
      AND (LAYOUT_NAME      ILIKE '%' || #{search_term} || '%'
        OR LAYOUT_NAME_ENG  ILIKE '%' || #{search_term} || '%'
        OR DESCRIPTION      ILIKE '%' || #{search_term} || '%')
    </if>
  </sql>

  <!-- 목록 조회 -->
  <select id="selectLayouts" parameterType="map" resultType="map">
    SELECT *
    FROM LAYOUT_STANDARDS
    <include refid="layoutWhereClause"/>
    ORDER BY SORT_ORDER ASC, CREATED_DATE DESC
    <include refid="common.pagination"/>
  </select>

  <!-- 총 개수 -->
  <select id="countLayouts" parameterType="map" resultType="int">
    SELECT COUNT(*)
    FROM LAYOUT_STANDARDS
    <include refid="layoutWhereClause"/>
  </select>

  <!-- 단건 조회 (읽기용: COMPANY_CODE OR IS_PUBLIC) -->
  <select id="selectLayoutByCode" parameterType="map" resultType="map">
    SELECT *
    FROM LAYOUT_STANDARDS
    WHERE LAYOUT_CODE = #{layout_code}
      AND IS_ACTIVE = 'Y'
      AND ((COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*') OR IS_PUBLIC = 'Y')
    LIMIT 1
  </select>

  <!-- 단건 조회 (쓰기 권한 확인용: COMPANY_CODE 엄격 일치) -->
  <select id="selectLayoutByCodeAndCompany" parameterType="map" resultType="map">
    SELECT *
    FROM LAYOUT_STANDARDS
    WHERE LAYOUT_CODE  = #{layout_code}
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
      AND IS_ACTIVE    = 'Y'
    LIMIT 1
  </select>

  <!-- 코드 자동 생성용: 패턴 일치 코드 목록 -->
  <select id="selectCodesLike" parameterType="map" resultType="map">
    SELECT LAYOUT_CODE
    FROM LAYOUT_STANDARDS
    WHERE LAYOUT_CODE LIKE #{prefix}
  </select>

  <!-- 레이아웃 생성 -->
  <insert id="insertLayout" parameterType="map">
    INSERT INTO LAYOUT_STANDARDS (
      LAYOUT_CODE, LAYOUT_NAME, LAYOUT_NAME_ENG, DESCRIPTION, LAYOUT_TYPE, CATEGORY,
      ICON_NAME, DEFAULT_SIZE, LAYOUT_CONFIG, ZONES_CONFIG, IS_PUBLIC, IS_ACTIVE,
      COMPANY_CODE, CREATED_BY, UPDATED_BY, CREATED_DATE, UPDATED_DATE, SORT_ORDER
    ) VALUES (
      #{layout_code}, #{layout_name}, #{layout_name_eng}, #{description}, #{layout_type}, #{category},
      #{icon_name},
      <choose>
        <when test="default_size != null">#{default_size}::JSONB</when>
        <otherwise>NULL</otherwise>
      </choose>,
      <choose>
        <when test="layout_config != null">#{layout_config}::JSONB</when>
        <otherwise>NULL</otherwise>
      </choose>,
      <choose>
        <when test="zones_config != null">#{zones_config}::JSONB</when>
        <otherwise>NULL</otherwise>
      </choose>,
      #{is_public}, 'Y', #{company_code}, #{user_id}, #{user_id}, NOW(), NOW(), 0
    )
  </insert>

  <!-- 레이아웃 수정 (동적 SET) -->
  <update id="updateLayout" parameterType="map">
    UPDATE LAYOUT_STANDARDS
    <set>
      UPDATED_BY   = #{user_id},
      UPDATED_DATE = NOW(),
      <if test="layout_name    != null">LAYOUT_NAME     = #{layout_name},</if>
      <if test="layout_name_eng != null">LAYOUT_NAME_ENG = #{layout_name_eng},</if>
      <if test="description   != null">DESCRIPTION     = #{description},</if>
      <if test="layout_type    != null">LAYOUT_TYPE     = #{layout_type},</if>
      <if test="category      != null">CATEGORY        = #{category},</if>
      <if test="icon_name      != null">ICON_NAME       = #{icon_name},</if>
      <if test="default_size   != null">DEFAULT_SIZE    = #{default_size}::JSONB,</if>
      <if test="layout_config  != null">LAYOUT_CONFIG   = #{layout_config}::JSONB,</if>
      <if test="zones_config   != null">ZONES_CONFIG    = #{zones_config}::JSONB,</if>
      <if test="is_public      != null">IS_PUBLIC       = #{is_public},</if>
    </set>
    WHERE LAYOUT_CODE  = #{layout_code}
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
      AND IS_ACTIVE    = 'Y'
  </update>

  <!-- 소프트 삭제 -->
  <update id="softDeleteLayout" parameterType="map">
    UPDATE LAYOUT_STANDARDS
    SET IS_ACTIVE    = 'N',
        UPDATED_BY   = #{user_id},
        UPDATED_DATE = NOW()
    WHERE LAYOUT_CODE  = #{layout_code}
      AND (COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*')
      AND IS_ACTIVE    = 'Y'
  </update>

  <!-- 카테고리별 개수 -->
  <select id="selectCountsByCategory" parameterType="map" resultType="map">
    SELECT CATEGORY, COUNT(*) AS COUNT
    FROM LAYOUT_STANDARDS
    WHERE IS_ACTIVE = 'Y'
      AND ((COMPANY_CODE = #{company_code} OR COMPANY_CODE = '*') OR IS_PUBLIC = 'Y')
    GROUP BY CATEGORY
  </select>

</mapper>
