-- +goose Up
-- +goose StatementBegin

-- 摸大红商品表
CREATE TABLE IF NOT EXISTS mohong_products (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(128) NOT NULL COMMENT '商品标题',
  cover_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '封面图',
  image_urls JSON NULL COMMENT '详情图列表',
  description TEXT NOT NULL COMMENT '商品描述',
  price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '售价(分)',
  original_price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '原价(分，0表示不展示)',
  unit VARCHAR(32) NOT NULL DEFAULT '份' COMMENT '单位',
  stock INT NOT NULL DEFAULT -1 COMMENT '库存，-1表示不限',
  sort_order INT NOT NULL DEFAULT 0 COMMENT '排序，越大越靠前',
  status VARCHAR(16) NOT NULL DEFAULT 'draft' COMMENT 'draft草稿 on_sale上架 off_sale下架',
  qrcode_image_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '专属固定二维码，空则用全局默认',
  created_by BIGINT UNSIGNED NULL COMMENT '创建管理员',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_mohong_products_status_sort (status, sort_order, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='摸大红商品';

-- 摸大红订单表
CREATE TABLE IF NOT EXISTS mohong_orders (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_no VARCHAR(64) NOT NULL COMMENT '订单号',
  user_id BIGINT UNSIGNED NOT NULL COMMENT '下单用户',
  product_id BIGINT UNSIGNED NOT NULL COMMENT '商品ID',
  quantity INT NOT NULL DEFAULT 1 COMMENT '数量',
  unit_price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '下单单价快照(分)',
  amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '应付总额(分)',
  status VARCHAR(32) NOT NULL DEFAULT 'pending_payment' COMMENT 'pending_payment/paid/completed/cancelled/refunded',
  product_snapshot JSON NULL COMMENT '商品快照',
  qrcode_url_snapshot VARCHAR(512) NOT NULL DEFAULT '' COMMENT '支付时解析的二维码快照',
  copy_text TEXT NOT NULL COMMENT '可复制订单文案',
  conversation_id BIGINT UNSIGNED NULL COMMENT '订单群会话ID',
  paid_at DATETIME NULL COMMENT '支付时间',
  completed_at DATETIME NULL COMMENT '完成时间',
  cancelled_at DATETIME NULL COMMENT '取消时间',
  cancel_reason VARCHAR(255) NOT NULL DEFAULT '' COMMENT '取消原因',
  admin_remark VARCHAR(255) NOT NULL DEFAULT '' COMMENT '后台备注',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_mohong_orders_order_no (order_no),
  KEY idx_mohong_orders_user_status (user_id, status, id),
  KEY idx_mohong_orders_product (product_id),
  KEY idx_mohong_orders_status_created (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='摸大红订单';

-- 会话表增加摸大红订单关联
ALTER TABLE chat_conversations
  ADD COLUMN mohong_order_id BIGINT UNSIGNED NULL COMMENT '摸大红订单ID' AFTER listing_id,
  ADD UNIQUE KEY uk_chat_conversations_mohong_order_id (mohong_order_id);

-- 业务配置
INSERT INTO system_configs (`key`, `value`, description) VALUES
('mohong.default_qrcode_url', '', '摸大红全局默认固定二维码图片URL'),
('mohong.group_welcome_text', '订单已支付，请扫码联系客服，并将下方订单信息复制发送给客服。', '摸大红订单群欢迎语'),
('mohong.order_copy_template', '【摸大红订单】\n订单号：{{order_no}}\n下单时间：{{created_at}}\n商品：{{product_title}}\n数量：{{quantity}}\n金额：{{amount}}\n下单人：{{buyer_name}}（{{buyer_phone}}）', '摸大红订单一键复制文案模板')
ON DUPLICATE KEY UPDATE description = VALUES(description);

-- 权限
INSERT INTO permissions (code, name, resource, action) VALUES
('mohong:product_view', '查看摸大红商品', 'mohong', 'product_view'),
('mohong:product_manage', '管理摸大红商品', 'mohong', 'product_manage'),
('mohong:order_view', '查看摸大红订单', 'mohong', 'order_view'),
('mohong:order_manage', '管理摸大红订单', 'mohong', 'order_manage'),
('mohong:config', '摸大红业务配置', 'mohong', 'config')
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  resource = VALUES(resource),
  action = VALUES(action);

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN (
  'mohong:product_view', 'mohong:product_manage',
  'mohong:order_view', 'mohong:order_manage',
  'mohong:config'
)
WHERE r.code = 'super_admin';

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN (
  'mohong:product_view', 'mohong:order_view', 'mohong:order_manage'
)
WHERE r.code = 'cs';

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin

DELETE rp FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.code IN (
  'mohong:product_view', 'mohong:product_manage',
  'mohong:order_view', 'mohong:order_manage',
  'mohong:config'
);

DELETE FROM permissions WHERE code IN (
  'mohong:product_view', 'mohong:product_manage',
  'mohong:order_view', 'mohong:order_manage',
  'mohong:config'
);

DELETE FROM system_configs WHERE `key` IN (
  'mohong.default_qrcode_url',
  'mohong.group_welcome_text',
  'mohong.order_copy_template'
);

ALTER TABLE chat_conversations
  DROP INDEX uk_chat_conversations_mohong_order_id,
  DROP COLUMN mohong_order_id;

DROP TABLE IF EXISTS mohong_orders;
DROP TABLE IF EXISTS mohong_products;

-- +goose StatementEnd
