-- +goose Up
-- +goose StatementBegin

ALTER TABLE chat_messages
  ADD COLUMN admin_attention_type VARCHAR(32) NOT NULL DEFAULT '' COMMENT '客服关注类型: user_inquiry用户咨询, order_paid支付成功' AFTER attachment_urls,
  ADD KEY idx_chat_messages_attention (conversation_id, admin_attention_type, id);

UPDATE chat_messages
SET admin_attention_type = 'user_inquiry'
WHERE sender_type = 'user' AND admin_attention_type = '';

INSERT INTO chat_admin_conversation_states (
  conversation_id, admin_user_id, remark, last_read_message_id, last_read_at
)
SELECT c.id, au.id, '', COALESCE(c.last_message_id, 0), c.last_message_at
FROM chat_conversations c
JOIN admin_users au ON au.status = 'active'
JOIN admin_user_roles aur ON aur.admin_user_id = au.id
JOIN roles r ON r.id = aur.role_id AND r.code = 'cs'
LEFT JOIN chat_admin_conversation_states cas
  ON cas.conversation_id = c.id AND cas.admin_user_id = au.id
WHERE cas.id IS NULL;

UPDATE chat_admin_conversation_states cas
JOIN chat_conversations c ON c.id = cas.conversation_id
SET cas.last_read_message_id = COALESCE(c.last_message_id, 0),
    cas.last_read_at = c.last_message_at
WHERE cas.last_read_message_id = 0;

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
ALTER TABLE chat_messages
  DROP KEY idx_chat_messages_attention,
  DROP COLUMN admin_attention_type;
-- +goose StatementEnd
