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

  <!-- 배송 목록 조회 -->
  <select id="getDeliveryList" parameterType="map" resultType="map">
    SELECT
      ID,
      TRACKING_NUMBER,
      CUSTOMER,
      ORIGIN,
      DESTINATION,
      STATUS,
      ESTIMATED_DELIVERY,
      DELAY_REASON,
      PRIORITY,
      CREATED_DATE
    FROM DELIVERIES
    WHERE DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
    ORDER BY CREATED_DATE DESC
  </select>

  <!-- 지연 배송 목록 조회 -->
  <select id="getDelayedDeliveryList" parameterType="map" resultType="map">
    SELECT
      ID,
      TRACKING_NUMBER,
      CUSTOMER,
      ORIGIN,
      DESTINATION,
      STATUS,
      ESTIMATED_DELIVERY,
      DELAY_REASON,
      PRIORITY,
      CREATED_DATE
    FROM DELIVERIES
    WHERE STATUS = 'delayed'
      AND DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
    ORDER BY ESTIMATED_DELIVERY ASC
  </select>

  <!-- 고객 이슈 목록 조회 -->
  <select id="getCustomerIssueList" parameterType="map" resultType="map">
    SELECT
      ID,
      CUSTOMER,
      TRACKING_NUMBER,
      ISSUE_TYPE,
      DESCRIPTION,
      STATUS,
      REPORTED_AT
    FROM CUSTOMER_ISSUES
    WHERE DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
    <if test="status != null and status != ''">
      AND STATUS = #{status}
    </if>
    ORDER BY REPORTED_AT DESC
  </select>

  <!-- 오늘 배송 통계 -->
  <select id="getDeliveryTodayStats" parameterType="map" resultType="map">
    SELECT
      COUNT(*) FILTER (WHERE STATUS = 'in_transit') AS shipped,
      COUNT(*) FILTER (WHERE STATUS = 'delivered') AS delivered
    FROM DELIVERIES
    WHERE DATE(CREATED_DATE) = CURRENT_DATE
      AND DELETED_DATE IS NULL
    <include refid="common.companyCodeFilter"/>
  </select>

  <!-- 배송 상태 업데이트 -->
  <update id="updateDeliveryStatus" parameterType="map">
    UPDATE DELIVERIES
    SET STATUS = #{status}
      , DELAY_REASON = #{delay_reason}
      , UPDATED_DATE = NOW()
    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <!-- 고객 이슈 상태 업데이트 -->
  <update id="updateCustomerIssueStatus" parameterType="map">
    UPDATE CUSTOMER_ISSUES
    SET STATUS = #{status}
      , UPDATED_DATE = NOW()
    WHERE ID = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

</mapper>
