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

  <sql id="scheduleSearchCondition">
    <if test="schedule_type != null and schedule_type != ''">
      AND schedule_type = #{schedule_type}
    </if>
    <if test="resource_type != null and resource_type != ''">
      AND resource_type = #{resource_type}
    </if>
    <if test="resource_id != null and resource_id != ''">
      AND resource_id = #{resource_id}
    </if>
    <if test="start_date != null and start_date != ''">
      AND end_date >= #{start_date}::date
    </if>
    <if test="end_date != null and end_date != ''">
      AND start_date &lt;= #{end_date}::date
    </if>
    <if test="status != null and status != ''">
      AND status = #{status}
    </if>
  </sql>

  <select id="getScheduleList" parameterType="map" resultType="map">
    SELECT SCHEDULE_ID, COALESCE(SCHEDULE_NO, '') AS SCHEDULE_NO, SCHEDULE_NAME, SCHEDULE_TYPE
        , RESOURCE_ID, RESOURCE_NAME, RESOURCE_TYPE
        , START_DATE, END_DATE, DUE_DATE
        , PLAN_QTY, COALESCE(ACTUAL_QTY, '') AS ACTUAL_QTY, COALESCE(UNIT, '') AS UNIT, COALESCE(PRIORITY, '') AS PRIORITY
        , STATUS, COALESCE(REMARKS, '') AS REMARKS, COMPANY_CODE
        , SOURCE_TABLE, SOURCE_ID, SOURCE_GROUP_KEY
        , AUTO_GENERATED, GENERATED_BY, GENERATED_AT, METADATA
        , CREATED_BY, CREATED_DATE AS CREATED_AT
        , UPDATED_BY, UPDATED_DATE AS UPDATED_AT
    FROM SCHEDULE_MNG

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="scheduleSearchCondition"/>

    ORDER BY start_date, resource_id
    <include refid="common.pagination"/>
  </select>

  <select id="getScheduleListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*) FROM schedule_mng

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="scheduleSearchCondition"/>
  </select>

  <select id="getScheduleInfo" parameterType="map" resultType="map">
    SELECT * FROM schedule_mng

    WHERE schedule_id = #{schedule_id}
    <include refid="common.companyCodeFilter"/>
  </select>

  <!-- 기존 자동생성 스케줄 조회 (preview 용) -->
  <select id="getExistingScheduleList" parameterType="map" resultType="map">
    SELECT * FROM schedule_mng

    WHERE schedule_type = #{schedule_type}
    <if test="resource_ids != null and !resource_ids.is_empty()">
      AND resource_id IN
      <foreach item="rid" collection="resourceIds" open="(" separator="," close=")">
        #{rid}
      </foreach>
    </if>
    AND end_date >= #{period_start}::date
    AND start_date &lt;= #{period_end}::date
    AND auto_generated = TRUE
    <include refid="common.companyCodeFilter"/>
  </select>

  <insert id="insertSchedule" parameterType="map" useGeneratedKeys="true" keyProperty="scheduleId" keyColumn="schedule_id">
    INSERT INTO schedule_mng (
      company_code, schedule_type, schedule_name,
      resource_type, resource_id, resource_name,
      start_date, end_date, due_date,
      plan_qty, unit, status, priority,
      source_table, source_id, source_group_key,
      auto_generated, generated_at, generated_by,
      metadata, created_by, updated_by
    ) VALUES (
      #{company_code}, #{schedule_type}, #{schedule_name},
      #{resource_type}, #{resource_id}, #{resource_name},
      #{start_date}::timestamp, #{end_date}::timestamp,
      <choose>
        <when test="due_date != null">#{due_date}::timestamp</when>
        <otherwise>NULL</otherwise>
      </choose>,
      #{plan_qty}, #{unit},
      <choose>
        <when test="status != null">#{status}</when>
        <otherwise>'PLANNED'</otherwise>
      </choose>,
      #{priority}, #{source_table}, #{source_id}, #{source_group_key},
      <choose>
        <when test="auto_generated != null">#{auto_generated}</when>
        <otherwise>TRUE</otherwise>
      </choose>,
      NOW(), #{generated_by},
      <choose>
        <when test="metadata != null">#{metadata}::jsonb</when>
        <otherwise>NULL</otherwise>
      </choose>,
      #{created_by}, #{updated_by}
    )
  </insert>

  <update id="updateSchedule" parameterType="map">
    UPDATE schedule_mng
    <set>
      <if test="status != null">status = #{status},</if>
      <if test="plan_qty != null">plan_qty = #{plan_qty},</if>
      <if test="start_date != null">start_date = #{start_date}::timestamp,</if>
      <if test="end_date != null">end_date = #{end_date}::timestamp,</if>
      <if test="updated_by != null">updated_by = #{updated_by},</if>
      schedule_id = #{schedule_id}
    </set>

    WHERE schedule_id = #{schedule_id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <delete id="deleteSchedule" parameterType="map">
    DELETE FROM schedule_mng

    WHERE schedule_id = #{schedule_id}
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- 다중 삭제 (apply 용) -->
  <delete id="deleteSchedulesByIdList" parameterType="map">
    DELETE FROM schedule_mng

    WHERE schedule_id IN
    <foreach item="id" collection="idList" open="(" separator="," close=")">
      #{id}
    </foreach>
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- 스케줄 이력 저장 -->
  <insert id="insertScheduleHistory" parameterType="map">
    INSERT INTO schedule_history (company_code, schedule_id, action, changed_by)
    VALUES (#{company_code}, #{schedule_id}, #{action}, #{changed_by})
  </insert>

</mapper>
