<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zioinfo.mall.schedule.mapper.ScheduleMapper">
  <select id="findSlots" resultType="com.zioinfo.mall.schedule.MallScheduleSlot">
    SELECT * FROM mall_schedule_slot
    WHERE store_id = #{storeId}
    <if test="slotDate != null">AND slot_date = #{slotDate}</if>
    AND active = TRUE
    ORDER BY slot_date, start_time
  </select>
  <select id="findSlot" resultType="com.zioinfo.mall.schedule.MallScheduleSlot">SELECT * FROM mall_schedule_slot WHERE id = #{id}</select>
  <insert id="insertSlot" parameterType="com.zioinfo.mall.schedule.MallScheduleSlot" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mall_schedule_slot (store_id, slot_date, slot_label, start_time, end_time, capacity, booked, surge_multiplier, active)
    VALUES (#{storeId}, #{slotDate}, #{slotLabel}, #{startTime}, #{endTime}, COALESCE(#{capacity},20),
            COALESCE(#{booked},0), COALESCE(#{surgeMultiplier},1.00), COALESCE(#{active},TRUE))
  </insert>
  <update id="bookSlot">UPDATE mall_schedule_slot SET booked = COALESCE(booked,0) + 1 WHERE id = #{id} AND booked &lt; capacity</update>
  <update id="setSlotActive">UPDATE mall_schedule_slot SET active = #{active} WHERE id = #{id}</update>

  <select id="findHolidays" resultType="com.zioinfo.mall.schedule.MallHoliday">SELECT * FROM mall_holiday ORDER BY holiday_date</select>
  <select id="findHoliday" resultType="com.zioinfo.mall.schedule.MallHoliday">
    SELECT * FROM mall_holiday
    WHERE holiday_date = #{date} AND (store_id = #{storeId} OR store_id IS NULL)
    ORDER BY store_id NULLS LAST LIMIT 1
  </select>
  <insert id="upsertHoliday" parameterType="com.zioinfo.mall.schedule.MallHoliday">
    INSERT INTO mall_holiday (holiday_date, name, blocked, surge_multiplier, store_id)
    VALUES (#{holidayDate}, #{name}, COALESCE(#{blocked},FALSE), COALESCE(#{surgeMultiplier},1.00), #{storeId})
    ON CONFLICT (holiday_date, store_id) DO UPDATE SET
      name = EXCLUDED.name, blocked = EXCLUDED.blocked, surge_multiplier = EXCLUDED.surge_multiplier
  </insert>
  <update id="setHolidayBlocked">UPDATE mall_holiday SET blocked = #{blocked} WHERE id = #{id}</update>
</mapper>
