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

  <sql id="bookingSearchCondition">
    <if test="status != null and status != ''">
      AND STATUS = #{status}
    </if>
    <if test="keyword != null and keyword != ''">
      AND (CUSTOMER_NAME ILIKE '%' || #{keyword} || '%'
        OR PICKUP_LOCATION ILIKE '%' || #{keyword} || '%'
        OR DROPOFF_LOCATION ILIKE '%' || #{keyword} || '%')
    </if>
  </sql>

  <!-- Node.js: ORDER BY CASE WHEN priority='urgent' THEN 0 ELSE 1 END, CREATED_DATE DESC -->
  <select id="getBookingList" parameterType="map" resultType="map">
    SELECT
        ID
        , CUSTOMER_NAME
        , CUSTOMER_PHONE
        , PICKUP_LOCATION
        , DROPOFF_LOCATION
        , SCHEDULED_TIME
        , VEHICLE_TYPE
        , CARGO_TYPE
        , WEIGHT
        , STATUS
        , PRIORITY
        , CREATED_DATE
        , UPDATED_DATE
        , ACCEPTED_AT
        , REJECTED_AT
        , COMPLETED_AT
        , NOTES
        , ESTIMATED_COST
        , REJECTION_REASON

    FROM BOOKING_REQUESTS

    WHERE 1=1
    <include refid="bookingSearchCondition"/>

    ORDER BY CASE WHEN PRIORITY = 'urgent' THEN 0 ELSE 1 END,
             CREATED_DATE DESC
    <include refid="common.pagination"/>
  </select>

  <select id="getBookingListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM BOOKING_REQUESTS

    WHERE 1=1
    <include refid="bookingSearchCondition"/>
  </select>

  <!-- pending 상태이고 5분 이내 생성된 건수 (newCount) -->
  <select id="getBookingNewCount" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM BOOKING_REQUESTS

    WHERE STATUS = 'pending'
      AND CREATED_DATE &gt;= NOW() - INTERVAL '5 minutes'
  </select>

  <!-- POST /:id/accept — status = 'accepted', accepted_at = NOW() -->
  <update id="acceptBooking" parameterType="map">
    UPDATE BOOKING_REQUESTS

    SET
        STATUS = 'accepted'
        , ACCEPTED_AT = NOW()
        , UPDATED_DATE = NOW()

    WHERE ID = #{id}
  </update>

  <!-- POST /:id/reject — status = 'rejected', rejected_at = NOW(), rejection_reason -->
  <update id="rejectBooking" parameterType="map">
    UPDATE BOOKING_REQUESTS

    SET
        STATUS = 'rejected'
        , REJECTED_AT = NOW()
        , UPDATED_DATE = NOW()
        , REJECTION_REASON = #{rejection_reason, jdbcType=VARCHAR}

    WHERE ID = #{id}
  </update>

</mapper>
