-- +goose Up
-- 高频客服列表不再实时扫描全部订单与聊天消息；以下字段是可由业务记录重建的读取快照。

ALTER TABLE chat_conversations
  ADD COLUMN latest_order_id BIGINT UNSIGNED NULL COMMENT '发布群最新订单ID快照' AFTER listing_id,
  ADD COLUMN latest_order_no VARCHAR(64) NOT NULL DEFAULT '' COMMENT '发布群最新订单号快照' AFTER latest_order_id,
  ADD COLUMN latest_order_status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '发布群最新订单状态快照' AFTER latest_order_no,
  ADD COLUMN latest_order_handoff_status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '发布群最新交接状态快照' AFTER latest_order_status,
  ADD COLUMN latest_order_refund_status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '发布群最新退款状态快照' AFTER latest_order_handoff_status,
  ADD COLUMN last_attention_message_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '最后一条需客服关注消息ID' AFTER latest_order_refund_status,
  ADD COLUMN last_admin_message_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '最后一条客服消息ID' AFTER last_attention_message_id,
  ADD KEY idx_chat_conversations_latest_order_status (latest_order_status, last_message_at, id);

UPDATE chat_conversations AS c
JOIN (
  SELECT ro.id, ro.listing_id, ro.order_no, ro.status, ro.handoff_status, ro.refund_status
  FROM rental_orders AS ro
  JOIN (
    SELECT listing_id, MAX(id) AS id
    FROM rental_orders
    GROUP BY listing_id
  ) AS latest ON latest.id = ro.id
) AS o ON o.listing_id = c.listing_id
SET c.latest_order_id = o.id,
    c.latest_order_no = o.order_no,
    c.latest_order_status = o.status,
    c.latest_order_handoff_status = o.handoff_status,
    c.latest_order_refund_status = o.refund_status
WHERE c.order_id IS NULL;

UPDATE chat_conversations AS c
LEFT JOIN (
  SELECT conversation_id,
    COALESCE(MAX(CASE WHEN admin_attention_type <> '' OR sender_type = 'user' THEN id END), 0) AS attention_id,
    COALESCE(MAX(CASE WHEN sender_type = 'admin' THEN id END), 0) AS admin_id
  FROM chat_messages
  GROUP BY conversation_id
) AS m ON m.conversation_id = c.id
SET c.last_attention_message_id = COALESCE(m.attention_id, 0),
    c.last_admin_message_id = COALESCE(m.admin_id, 0);

-- +goose Down

ALTER TABLE chat_conversations
  DROP KEY idx_chat_conversations_latest_order_status,
  DROP COLUMN last_admin_message_id,
  DROP COLUMN last_attention_message_id,
  DROP COLUMN latest_order_refund_status,
  DROP COLUMN latest_order_handoff_status,
  DROP COLUMN latest_order_status,
  DROP COLUMN latest_order_no,
  DROP COLUMN latest_order_id;
