-- +goose Up
-- +goose StatementBegin

-- 1. chat_conversations 表新增 listing_id 列
ALTER TABLE chat_conversations
  ADD COLUMN listing_id BIGINT UNSIGNED NULL COMMENT '关联的发布ID(listing_group类型会话使用)',
  ADD INDEX idx_chat_conversations_listing (listing_id);

-- 2. 新建 chat_qrcode_pool 表(企业微信群二维码池)
CREATE TABLE IF NOT EXISTS chat_qrcode_pool (
  id              BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  image_url       VARCHAR(512) NOT NULL COMMENT 'MinIO存储的二维码图片URL',
  status          VARCHAR(16) NOT NULL DEFAULT 'unused' COMMENT '状态: unused/used/disabled',
  conversation_id BIGINT UNSIGNED NULL COMMENT '发出后记录到哪个发布群(留痕)',
  used_at         DATETIME NULL COMMENT '使用时间',
  expires_at      DATETIME NULL COMMENT '企微群码失效时间(默认创建+7天)',
  created_by      BIGINT UNSIGNED NOT NULL COMMENT '上传的客服 admin_id',
  note            VARCHAR(255) NOT NULL DEFAULT '' COMMENT '备注,如"7月企微群A"',
  created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_qrcode_status (status),
  INDEX idx_qrcode_expires (expires_at),
  INDEX idx_qrcode_conversation (conversation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='企业微信群二维码池';

-- 3. 新增 system_configs 配置项(system_configs 表只有 key/value/description 三列)
INSERT INTO system_configs (`key`, `value`, description) VALUES
  ('chat.listing_group_welcome', '欢迎加入账号群！请号主扫描下方二维码加入企业微信群，方便客服与您及时联系。', '发布群欢迎语'),
  ('chat.qrcode_low_stock_threshold', '5', '二维码库存预警阈值')
ON DUPLICATE KEY UPDATE
  `value` = VALUES(`value`),
  description = VALUES(description);

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin

-- 回滚配置项
DELETE FROM system_configs WHERE `key` IN ('chat.listing_group_welcome', 'chat.qrcode_low_stock_threshold');

-- 回滚表
DROP TABLE IF EXISTS chat_qrcode_pool;

-- 回滚列
ALTER TABLE chat_conversations
  DROP INDEX idx_chat_conversations_listing,
  DROP COLUMN listing_id;

-- +goose StatementEnd
