<?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="com.zioinfo.signage.mapper.UpdateQueueMapper">

  <resultMap id="queueMap" type="com.zioinfo.signage.domain.UpdateQueueVo">
    <id property="id"             column="id"/>
    <result property="tenantCode"     column="tenant_code"/>
    <result property="storeId"        column="store_id"/>
    <result property="storeName"      column="store_name"/>
    <result property="bindingId"      column="binding_id"/>
    <result property="deviceId"       column="device_id"/>
    <result property="locationCode"   column="location_code"/>
    <result property="productCode"    column="product_code"/>
    <result property="productName"    column="product_name"/>
    <result property="newPrice"       column="new_price"/>
    <result property="newSalePrice"   column="new_sale_price"/>
    <result property="templateCode"   column="template_code"/>
    <result property="renderData"     column="render_data"/>
    <result property="priority"       column="priority"/>
    <result property="status"         column="status"/>
    <result property="retryCount"     column="retry_count"/>
    <result property="maxRetry"       column="max_retry"/>
    <result property="errorMessage"   column="error_message"/>
    <result property="posCvtId"       column="pos_cvt_id"/>
    <result property="sentAt"         column="sent_at"/>
    <result property="confirmedAt"    column="confirmed_at"/>
    <result property="createdAt"      column="created_at"/>
  </resultMap>

  <select id="findAll" resultMap="queueMap">
    SELECT q.id, q.tenant_code, q.store_id, s.store_name,
           q.binding_id, q.device_id, b.location_code,
           q.product_code, p.product_name,
           q.new_price, q.new_sale_price, q.template_code, q.render_data,
           q.priority, q.status, q.retry_count, q.max_retry, q.error_message,
           q.pos_cvt_id, q.sent_at, q.confirmed_at, q.created_at
    FROM signage_update_queue q
    LEFT JOIN signage_store s        ON q.store_id = s.id
    LEFT JOIN signage_signboard b  ON q.binding_id = b.id
    LEFT JOIN signage_product p      ON q.store_id = p.store_id AND q.product_code = p.product_code
    <where>
      <if test="tenantCode != null and tenantCode != ''">AND q.tenant_code = #{tenantCode}</if>
      <if test="storeId != null">AND q.store_id = #{storeId}</if>
      <if test="status != null and status != ''">AND q.status = #{status}</if>
    </where>
    ORDER BY q.priority ASC, q.created_at ASC
    LIMIT 200
  </select>

  <!-- Gateway가 전송할 PENDING 목록 (우선순위·시간 순) -->
  <select id="findPending" resultMap="queueMap">
    SELECT q.id, q.tenant_code, q.store_id, s.store_name,
           q.binding_id, q.device_id, b.location_code,
           q.product_code, p.product_name,
           q.new_price, q.new_sale_price, q.template_code, q.render_data,
           q.priority, q.status, q.retry_count, q.max_retry, q.error_message,
           q.pos_cvt_id, q.sent_at, q.confirmed_at, q.created_at
    FROM signage_update_queue q
    LEFT JOIN signage_store s        ON q.store_id = s.id
    LEFT JOIN signage_signboard b  ON q.binding_id = b.id
    LEFT JOIN signage_product p      ON q.store_id = p.store_id AND q.product_code = p.product_code
    WHERE q.status = 'PENDING'
      AND q.retry_count &lt; q.max_retry
      <if test="tenantCode != null and tenantCode != ''">AND q.tenant_code = #{tenantCode}</if>
    ORDER BY q.priority ASC, q.created_at ASC
    LIMIT #{limit}
  </select>

  <select id="findById" resultMap="queueMap">
    SELECT q.id, q.tenant_code, q.store_id, s.store_name,
           q.binding_id, q.device_id, b.location_code,
           q.product_code, p.product_name,
           q.new_price, q.new_sale_price, q.template_code, q.render_data,
           q.priority, q.status, q.retry_count, q.max_retry, q.error_message,
           q.pos_cvt_id, q.sent_at, q.confirmed_at, q.created_at
    FROM signage_update_queue q
    LEFT JOIN signage_store s        ON q.store_id = s.id
    LEFT JOIN signage_signboard b  ON q.binding_id = b.id
    LEFT JOIN signage_product p      ON q.store_id = p.store_id AND q.product_code = p.product_code
    WHERE q.id = #{id}
  </select>

  <insert id="insert" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO signage_update_queue
      (tenant_code, store_id, binding_id, device_id, product_code,
       new_price, new_sale_price, template_code, priority, status, pos_cvt_id)
    VALUES
      (#{tenantCode}, #{storeId}, #{bindingId}, #{deviceId}, #{productCode},
       #{newPrice}, #{newSalePrice}, #{templateCode}, #{priority}, 'PENDING', #{posCvtId})
  </insert>

  <update id="updateStatus">
    UPDATE signage_update_queue SET
      status        = #{status},
      error_message = #{errorMessage},
      sent_at       = CASE WHEN #{status} = 'SENT' THEN NOW() ELSE sent_at END,
      confirmed_at  = CASE WHEN #{status} = 'CONFIRMED' THEN NOW() ELSE confirmed_at END
    WHERE id = #{id}
  </update>

  <!-- 태그가 확인 응답 시 — device_id로 SENT → CONFIRMED -->
  <update id="confirmByDeviceId">
    UPDATE signage_update_queue SET
      status       = 'CONFIRMED',
      confirmed_at = NOW()
    WHERE device_id = #{deviceId}
      AND status IN ('SENDING', 'SENT')
  </update>

  <update id="incrementRetry">
    UPDATE signage_update_queue SET retry_count = retry_count + 1
    WHERE id = #{id}
  </update>

  <select id="countPending" resultType="long">
    SELECT COUNT(*) FROM signage_update_queue WHERE status = 'PENDING'
    <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
  </select>

  <select id="countFailed" resultType="long">
    SELECT COUNT(*) FROM signage_update_queue WHERE status = 'FAILED'
    <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
  </select>

  <select id="countByStatus" resultType="long">
    SELECT COUNT(*) FROM signage_update_queue WHERE status = #{status}
    <if test="tenantCode != null and tenantCode != ''">AND tenant_code = #{tenantCode}</if>
  </select>

</mapper>
