<?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">
<!--
  DesignMapper — M3 부스 설계안(버전). spec 은 jsonb.
  파라미터 계약: upsertDesign params {designId?, boothId, version, status, specJson(JSON 문자열)}.
  findDesign 반환: spec 은 specJson(문자열) — 백엔드가 DesignSpec 으로 역직렬화.
-->
<mapper namespace="com.zioinfo.kintex.module.m3.mapper.DesignMapper">

    <!-- 설계안 조회(version=null → 최신). -->
    <select id="findDesign" resultType="map">
        SELECT id          AS "designId",
               booth_id    AS "boothId",
               version,
               status,
               spec::text  AS "specJson",
               to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "updatedAt"
        FROM design_plan
        WHERE booth_id = #{boothId}
        <if test="version != null">
          AND version = #{version}
        </if>
        ORDER BY version DESC
        LIMIT 1
    </select>

    <!-- 설계안 upsert → designId 반환. -->
    <select id="upsertDesign" resultType="string">
        INSERT INTO design_plan (id, booth_id, version, status, spec, updated_at)
        VALUES (COALESCE(#{params.designId}, gen_random_uuid()::text),
                #{params.boothId},
                COALESCE(#{params.version}, 1),
                COALESCE(#{params.status}, 'draft'),
                CAST(#{params.specJson} AS jsonb),
                now())
        ON CONFLICT (booth_id, version) DO UPDATE
            SET status     = EXCLUDED.status,
                spec       = EXCLUDED.spec,
                updated_at = now()
        RETURNING id
    </select>

    <!-- 부스 → 행사 역참조(RBAC 확인용). -->
    <select id="findEventIdByBooth" resultType="string">
        SELECT l.event_id
        FROM booth b
        JOIN layout l ON l.id = b.layout_id
        WHERE b.id = #{boothId}
    </select>

</mapper>
