-- ============================================
-- 数据库初始化脚本 (合并版本)
-- 包含所有表结构、索引和基础数据
-- 创建时间: 2026-06-05
-- ============================================

-- +goose Up

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- -------------------------------------------
-- 用户相关表
-- -------------------------------------------

-- 用户主表：存储用户基本信息、实名状态、风控状态等
CREATE TABLE IF NOT EXISTS users (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  phone VARCHAR(32) NOT NULL COMMENT '手机号',
  nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称',
  avatar_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '头像URL',
  realname_status VARCHAR(32) NOT NULL DEFAULT 'unverified' COMMENT '实名状态: unverified未实名, pending审核中, verified已实名, failed失败',
  risk_status VARCHAR(32) NOT NULL DEFAULT 'normal' COMMENT '风控状态: normal正常, warning警告, frozen冻结',
  credit_score INT NOT NULL DEFAULT 100 COMMENT '信用分',
  deposit_free_quota_cent BIGINT NOT NULL DEFAULT 0 COMMENT '免押总额度(分)',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '账号状态: active活跃, inactive停用, banned封禁',
  last_login_at DATETIME NULL COMMENT '最后登录时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_users_phone (phone),
  KEY idx_users_realname_status (realname_status, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';

-- 用户实名认证记录表
CREATE TABLE IF NOT EXISTS user_realname (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  provider VARCHAR(32) NOT NULL COMMENT '认证服务商',
  provider_order_no VARCHAR(128) NOT NULL DEFAULT '' COMMENT '服务商订单号',
  status VARCHAR(32) NOT NULL DEFAULT 'pending' COMMENT '认证状态: pending待处理, success成功, failed失败',
  masked_name VARCHAR(64) NOT NULL DEFAULT '' COMMENT '脱敏姓名',
  encrypted_name VARCHAR(255) NOT NULL DEFAULT '' COMMENT '加密的完整姓名',
  masked_id_no VARCHAR(64) NOT NULL DEFAULT '' COMMENT '脱敏身份证号',
  encrypted_id_no VARCHAR(255) NOT NULL DEFAULT '' COMMENT '加密的完整身份证号',
  verified_at DATETIME NULL COMMENT '认证通过时间',
  fail_reason 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_user_realname_user_id (user_id),
  KEY idx_user_realname_provider_order_no (provider_order_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户实名认证记录';

-- -------------------------------------------
-- 游戏账号和商品表
-- -------------------------------------------

-- 游戏账号表：存储用户的游戏账号信息
CREATE TABLE IF NOT EXISTS game_accounts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  owner_id BIGINT UNSIGNED NOT NULL COMMENT '账号所有者ID',
  game_name VARCHAR(64) NOT NULL DEFAULT 'delta_force' COMMENT '游戏名称',
  server_region VARCHAR(64) NOT NULL COMMENT '服务器区域',
  login_platform VARCHAR(64) NOT NULL COMMENT '登录平台: steam/epic/wegame等',
  title VARCHAR(128) NOT NULL COMMENT '账号标题',
  description TEXT NULL COMMENT '账号描述',
  rank_level VARCHAR(64) NOT NULL DEFAULT '' COMMENT '段位等级',
  haf_coin_amount BIGINT NOT NULL DEFAULT 0 COMMENT 'HAF币数量',
  asset_summary JSON NULL COMMENT '资产摘要(JSON格式)',
  season_tags JSON NULL COMMENT '赛季标签(JSON数组)',
  screenshot_urls JSON NULL COMMENT '截图URL列表(JSON数组)',
  status VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT '状态: draft草稿, active使用中, deleted已删除',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_game_accounts_owner_id (owner_id),
  KEY idx_game_accounts_filter (game_name, server_region, login_platform)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏账号表';

-- 租号商品列表：用户发布的出租商品
CREATE TABLE IF NOT EXISTS rental_listings (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  listing_no VARCHAR(20) NOT NULL COMMENT '商品编号，格式yyyyMMddNNNN',
  account_id BIGINT UNSIGNED NOT NULL COMMENT '关联的游戏账号ID',
  owner_id BIGINT UNSIGNED NOT NULL COMMENT '号主ID',
  price_cent BIGINT NOT NULL DEFAULT 0 COMMENT '租金(分/小时)',
  deposit_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '押金金额(分)',
  in_transaction TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否正在交易中: 0否, 1是',
  status VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT '商品状态: draft草稿, active上架, offline下架, deleted删除',
  review_status VARCHAR(32) NOT NULL DEFAULT 'none' COMMENT '审核状态: none无需审核, pending待审核, approved通过, rejected拒绝',
  review_reason VARCHAR(255) NOT NULL DEFAULT '' COMMENT '审核拒绝原因',
  published_at DATETIME NULL COMMENT '发布时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_rental_listings_listing_no (listing_no),
  KEY idx_rental_listings_account_id (account_id),
  KEY idx_rental_listings_owner_id (owner_id),
  KEY idx_rental_listings_filter (status, review_status, in_transaction, price_cent),
  KEY idx_rental_listings_published (status, review_status, published_at DESC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='租号商品列表';

-- 商品编号日序列表：记录每天已分配的最大序号
CREATE TABLE IF NOT EXISTS listing_no_sequences (
  biz_date CHAR(8) PRIMARY KEY COMMENT '业务日期yyyyMMdd',
  next_seq INT NOT NULL DEFAULT 0 COMMENT '当日已分配最大序号',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品编号日序列表';

-- -------------------------------------------
-- 订单相关表
-- -------------------------------------------

-- 租号订单表：核心订单信息
CREATE TABLE IF NOT EXISTS rental_orders (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_no VARCHAR(64) NOT NULL COMMENT '订单号',
  listing_id BIGINT UNSIGNED NOT NULL COMMENT '商品ID',
  account_id BIGINT UNSIGNED NOT NULL COMMENT '游戏账号ID',
  owner_id BIGINT UNSIGNED NOT NULL COMMENT '号主ID',
  renter_id BIGINT UNSIGNED NOT NULL COMMENT '租客ID',
  rented_at DATETIME NULL COMMENT '租用开始时间',
  estimated_duration_hours INT NOT NULL DEFAULT 24 COMMENT '预计租用时长(小时)',
  rent_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '租金总额(分)',
  owner_rent_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '号主实得租金(分)',
  deposit_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '实际收取押金(分)',
  deposit_original_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '商品原始押金(分)',
  deposit_waived_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '免押抵扣金额(分)',
  platform_fee_cent BIGINT NOT NULL DEFAULT 0 COMMENT '平台手续费(分)',
  account_snapshot JSON NULL COMMENT '账号快照(下单时的账号状态)',
  status VARCHAR(32) NOT NULL DEFAULT 'pending_payment' COMMENT '订单状态: pending_payment待支付, active进行中, completed已完成, cancelled已取消, closed已关闭',
  handoff_status VARCHAR(32) NOT NULL DEFAULT 'none' COMMENT '交接状态: none未开始, owner_delivered号主已交, renter_confirmed租客已确认, renter_returned租客已还, owner_received号主已收',
  settlement_status VARCHAR(32) NOT NULL DEFAULT 'unsettled' COMMENT '结算状态: unsettled未结算, owner_settled号主已结算, settled完全结算',
  refund_status VARCHAR(32) NOT NULL DEFAULT 'none' COMMENT '退款状态: none无退款, pending待退款, processing退款中, success退款成功, failed退款失败',
  refund_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '退款金额(分)',
  refunded_at DATETIME NULL COMMENT '退款完成时间',
  owner_settled_at DATETIME NULL COMMENT '号主结算时间',
  settled_at DATETIME NULL COMMENT '订单结算时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_rental_orders_order_no (order_no),
  KEY idx_rental_orders_renter_status (renter_id, status),
  KEY idx_rental_orders_owner_status (owner_id, status),
  KEY idx_rental_orders_listing_id (listing_id),
  KEY idx_rental_orders_refund_status (refund_status),
  KEY idx_rental_orders_rented_at (status, rented_at),
  KEY idx_rental_orders_status_created_at (status, created_at DESC),
  KEY idx_rental_orders_settlement (settlement_status, owner_id, created_at),
  KEY idx_rental_orders_settled_at_id (settled_at, id),
  KEY idx_rental_orders_created_at_id (created_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='租号订单表';

-- 订单结算记录表：记录租用完成后的结算信息
CREATE TABLE IF NOT EXISTS order_checkouts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
  initiated_by BIGINT UNSIGNED NOT NULL COMMENT '发起者ID',
  status VARCHAR(32) NOT NULL DEFAULT 'submitted' COMMENT '结算状态: submitted已提交, renter_confirmed租客确认, renter_rejected租客拒绝, completed完成',
  rent_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '租金(分)',
  owner_rent_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '号主实得租金(分)',
  platform_fee_cent BIGINT NOT NULL DEFAULT 0 COMMENT '平台手续费(分)',
  deposit_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '押金(分)',
  consumable_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '消耗品扣费(分)',
  coin_consumed_m DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '游戏币消耗(百万为单位)',
  other_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '其他费用(分)',
  deposit_deduct_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '押金扣除金额(分)',
  renter_refund_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '租客退款金额(分)',
  owner_income_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '号主收入金额(分)',
  content TEXT NULL COMMENT '结算说明',
  evidence_urls JSON NULL COMMENT '证据截图URL列表',
  owner_adjustment_reason TEXT NULL COMMENT '号主调整原因',
  owner_adjusted_at DATETIME NULL COMMENT '号主调整时间',
  renter_confirmed_at DATETIME NULL COMMENT '租客确认时间',
  renter_rejected_at DATETIME NULL COMMENT '租客拒绝时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_order_checkouts_order_id (order_id),
  KEY idx_order_checkouts_status (status),
  KEY idx_order_checkouts_status_order_id_id (status, order_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单结算记录表';

-- 账号交接记录表：记录号主和租客之间的账号交接
CREATE TABLE IF NOT EXISTS handoff_records (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
  from_user_id BIGINT UNSIGNED NOT NULL COMMENT '交出方用户ID',
  to_user_id BIGINT UNSIGNED NOT NULL COMMENT '接收方用户ID',
  type VARCHAR(32) NOT NULL COMMENT '交接类型: deliver交付, return归还',
  content TEXT NULL COMMENT '交接内容(账号密码等)',
  attachment_urls JSON NULL COMMENT '附件URL列表',
  confirmed_by_renter_at DATETIME NULL COMMENT '租客确认时间',
  confirmed_by_owner_at DATETIME NULL COMMENT '号主确认时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_handoff_records_order_id (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号交接记录表';

-- -------------------------------------------
-- 钱包相关表
-- -------------------------------------------

-- 钱包账户表：用户的虚拟钱包
CREATE TABLE IF NOT EXISTS wallet_accounts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  available_balance_cent BIGINT NOT NULL DEFAULT 0 COMMENT '可用余额(分)',
  frozen_balance_cent BIGINT NOT NULL DEFAULT 0 COMMENT '冻结余额(分)',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '钱包状态: active正常, frozen冻结, closed关闭',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_wallet_accounts_user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='钱包账户表';

-- 钱包流水表：记录所有的资金变动
CREATE TABLE IF NOT EXISTS wallet_ledger (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  ledger_no VARCHAR(64) NOT NULL COMMENT '流水号',
  user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  order_id BIGINT UNSIGNED NULL COMMENT '关联订单ID',
  direction VARCHAR(16) NOT NULL COMMENT '方向: in收入, out支出',
  amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '金额(分)',
  balance_after_cent BIGINT NOT NULL DEFAULT 0 COMMENT '变动后余额(分)',
  balance_type VARCHAR(32) NOT NULL COMMENT '余额类型: available可用, frozen冻结',
  biz_type VARCHAR(32) NOT NULL COMMENT '业务类型: rent_payment租金支付, deposit_freeze押金冻结, settlement结算, refund退款等',
  biz_no VARCHAR(64) NOT NULL COMMENT '业务单号',
  remark VARCHAR(255) NOT NULL DEFAULT '' COMMENT '备注',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_wallet_ledger_ledger_no (ledger_no),
  KEY idx_wallet_ledger_user_created (user_id, created_at),
  KEY idx_wallet_ledger_order_id (order_id),
  KEY idx_wallet_ledger_biz (biz_type, biz_no),
  KEY idx_wallet_ledger_user_biz_created (user_id, biz_type, created_at DESC),
  KEY idx_wallet_ledger_order_direction_biz (order_id, direction, biz_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='钱包流水表';

-- -------------------------------------------
-- 支付渠道订单表
-- -------------------------------------------

-- 支付订单表：对接第三方支付的订单记录
CREATE TABLE IF NOT EXISTS payment_orders (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  payment_no VARCHAR(64) NOT NULL COMMENT '支付单号',
  order_id BIGINT UNSIGNED NOT NULL COMMENT '关联订单ID',
  order_no VARCHAR(64) NOT NULL COMMENT '业务订单号',
  user_id BIGINT UNSIGNED NOT NULL COMMENT '支付用户ID',
  provider VARCHAR(32) NOT NULL COMMENT '支付服务商: leshua乐刷, lakala拉卡拉, mock模拟',
  merchant_id VARCHAR(128) NOT NULL DEFAULT '' COMMENT '商户号',
  third_order_id VARCHAR(64) NOT NULL COMMENT '第三方订单ID',
  provider_order_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '支付渠道订单号',
  pay_way VARCHAR(16) NOT NULL DEFAULT '' COMMENT '支付方式',
  jspay_flag VARCHAR(8) NOT NULL DEFAULT '' COMMENT 'JS支付标识',
  amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '支付金额(分)',
  biz_type VARCHAR(32) NOT NULL DEFAULT 'order_pay' COMMENT '业务类型: order_pay订单支付, wallet_recharge钱包充值',
  status VARCHAR(32) NOT NULL DEFAULT 'created' COMMENT '支付状态: created已创建, pending待支付, paid已支付, failed失败, cancelled取消',
  td_code VARCHAR(512) NOT NULL DEFAULT '' COMMENT '交易码',
  jspay_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT 'JS支付URL',
  jspay_info TEXT NULL COMMENT 'JS支付信息',
  raw_request JSON NULL COMMENT '原始请求(JSON)',
  raw_response JSON NULL COMMENT '原始响应(JSON)',
  paid_at DATETIME NULL COMMENT '支付完成时间',
  notified_at DATETIME NULL COMMENT '通知回调时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_payment_orders_payment_no (payment_no),
  UNIQUE KEY uk_payment_orders_third_order_id (third_order_id),
  KEY idx_payment_orders_order_id (order_id),
  KEY idx_payment_orders_order_no (order_no),
  KEY idx_payment_orders_user_id (user_id),
  KEY idx_payment_orders_provider_order_id (provider_order_id),
  KEY idx_payment_orders_biz_type (biz_type),
  KEY idx_payment_orders_status (status),
  KEY idx_payment_orders_order_biz_status (order_id, biz_type, status),
  KEY idx_payment_orders_created_biz_status (created_at, biz_type, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付订单表';

-- 支付商户配置表：支持多商户、多渠道支付配置
CREATE TABLE IF NOT EXISTS payment_merchant_configs (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(128) NOT NULL COMMENT '商户配置名称（用于识别）',
  provider VARCHAR(32) NOT NULL COMMENT '支付服务商: leshua乐刷, lakala拉卡拉, mock模拟',
  merchant_id VARCHAR(128) NOT NULL COMMENT '商户号',
  gateway_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '支付网关地址',
  sign_key TEXT NULL COMMENT '签名密钥/商户私钥（加密存储）',
  notify_key TEXT NULL COMMENT '通知验签密钥/平台通知证书（加密存储）',
  notify_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '异步通知回调地址',
  jump_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '支付完成跳转地址',
  pay_way VARCHAR(32) NOT NULL DEFAULT 'ZFBZF' COMMENT '支付方式: ZFBZF支付宝, WXZF微信',
  jspay_flag VARCHAR(8) NOT NULL DEFAULT '2' COMMENT 'JS支付标识: 1 H5, 2 小程序',
  sign_type VARCHAR(32) NOT NULL DEFAULT 'MD5' COMMENT '签名类型: MD5, SHA256withRSA',
  extra_config JSON NULL COMMENT '扩展配置（JSON格式）',
  is_default TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否默认商户: 0否, 1是（每个provider只能有一个默认）',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '状态: active启用, disabled禁用, testing测试中',
  environment VARCHAR(16) NOT NULL DEFAULT 'production' COMMENT '环境: production生产, sandbox测试',
  business_tags JSON NULL COMMENT '业务场景标签，如 ["order_pay", "wallet_recharge"]',
  total_transactions BIGINT NOT NULL DEFAULT 0 COMMENT '总交易笔数',
  total_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '总交易金额（分）',
  last_used_at DATETIME NULL COMMENT '最后使用时间',
  created_by BIGINT UNSIGNED NULL COMMENT '创建人（管理员ID）',
  updated_by BIGINT UNSIGNED NULL COMMENT '最后更新人（管理员ID）',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_payment_merchant_configs_provider (provider, status),
  KEY idx_payment_merchant_configs_default (provider, is_default),
  KEY idx_payment_merchant_configs_merchant_id (merchant_id),
  KEY idx_payment_merchant_configs_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付商户配置表';

-- 支付配置使用日志：用于追踪支付配置命中情况
CREATE TABLE IF NOT EXISTS payment_config_usage_logs (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  config_id BIGINT UNSIGNED NOT NULL COMMENT '商户配置ID',
  payment_order_id BIGINT UNSIGNED NOT NULL COMMENT '支付订单ID',
  provider VARCHAR(32) NOT NULL COMMENT '支付服务商',
  merchant_id VARCHAR(128) NOT NULL COMMENT '商户号',
  amount_cent BIGINT NOT NULL COMMENT '交易金额（分）',
  biz_type VARCHAR(32) NOT NULL COMMENT '业务类型',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_payment_config_usage_logs_config (config_id, created_at),
  KEY idx_payment_config_usage_logs_payment (payment_order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付配置使用日志';

-- -------------------------------------------
-- 纠纷和通知表
-- -------------------------------------------

-- 纠纷表：记录用户之间的交易纠纷
CREATE TABLE IF NOT EXISTS disputes (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
  initiator_id BIGINT UNSIGNED NOT NULL COMMENT '发起人ID',
  target_user_id BIGINT UNSIGNED NOT NULL COMMENT '被投诉人ID',
  type VARCHAR(32) NOT NULL COMMENT '纠纷类型: account_issue账号问题, payment_issue支付问题, behavior违规行为等',
  status VARCHAR(32) NOT NULL DEFAULT 'open' COMMENT '状态: open待处理, investigating调查中, resolved已解决, closed已关闭',
  description TEXT NULL COMMENT '纠纷描述',
  evidence_urls JSON NULL COMMENT '证据截图URL列表',
  arbitration_result VARCHAR(32) NOT NULL DEFAULT '' COMMENT '仲裁结果: owner_win号主胜, renter_win租客胜, draw平局',
  arbitration_remark TEXT NULL COMMENT '仲裁说明',
  handled_by BIGINT UNSIGNED NULL COMMENT '处理人ID(管理员)',
  handled_at DATETIME NULL COMMENT '处理时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_disputes_order_id (order_id),
  KEY idx_disputes_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='纠纷表';

-- 通知消息表：系统通知、订单通知等
CREATE TABLE IF NOT EXISTS notifications (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '接收用户ID',
  type VARCHAR(32) NOT NULL COMMENT '通知类型: system系统, order订单, chat聊天, wallet钱包',
  title VARCHAR(128) NOT NULL COMMENT '通知标题',
  content TEXT NULL COMMENT '通知内容',
  biz_type VARCHAR(32) NOT NULL DEFAULT '' COMMENT '业务类型',
  biz_id BIGINT UNSIGNED NULL COMMENT '业务ID',
  read_at DATETIME NULL COMMENT '已读时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_notifications_user_read_created (user_id, read_at, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='通知消息表';

-- 审计日志表：记录重要操作的审计日志
CREATE TABLE IF NOT EXISTS audit_logs (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  actor_type VARCHAR(32) NOT NULL COMMENT '操作者类型: user用户, admin管理员, system系统',
  actor_id BIGINT UNSIGNED NOT NULL COMMENT '操作者ID',
  action VARCHAR(64) NOT NULL COMMENT '操作动作',
  biz_type VARCHAR(32) NOT NULL COMMENT '业务类型',
  biz_id BIGINT UNSIGNED NULL COMMENT '业务ID',
  ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP地址',
  user_agent VARCHAR(512) NOT NULL DEFAULT '' COMMENT 'User-Agent',
  detail JSON NULL COMMENT '详细信息(JSON)',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_audit_logs_actor_created (actor_id, created_at),
  KEY idx_audit_logs_biz (biz_type, biz_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志表';

-- -------------------------------------------
-- 管理员和权限表
-- -------------------------------------------

-- 管理员表
CREATE TABLE IF NOT EXISTS admin_users (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  username VARCHAR(64) NOT NULL COMMENT '用户名',
  password_hash VARCHAR(255) NOT NULL COMMENT '密码哈希',
  nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '状态: active正常, inactive停用',
  support_status VARCHAR(16) NOT NULL DEFAULT 'offline' COMMENT '客服状态: online在线, offline离线, busy忙碌',
  token_version BIGINT NOT NULL DEFAULT 1 COMMENT '后台凭证版本，递增后旧 token 失效',
  password_must_change TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须先修改密码',
  last_login_at DATETIME NULL COMMENT '最后登录时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_admin_users_username (username),
  KEY idx_admin_users_support_status (support_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='管理员表';

-- 角色表
CREATE TABLE IF NOT EXISTS roles (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  code VARCHAR(64) NOT NULL COMMENT '角色代码',
  name VARCHAR(64) NOT NULL COMMENT '角色名称',
  description 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_roles_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色表';

-- 权限表
CREATE TABLE IF NOT EXISTS permissions (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  code VARCHAR(128) NOT NULL COMMENT '权限代码',
  name VARCHAR(64) NOT NULL COMMENT '权限名称',
  resource VARCHAR(128) NOT NULL COMMENT '资源',
  action VARCHAR(64) NOT NULL COMMENT '操作',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_permissions_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='权限表';

-- 管理员角色关联表
CREATE TABLE IF NOT EXISTS admin_user_roles (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  admin_user_id BIGINT UNSIGNED NOT NULL COMMENT '管理员ID',
  role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_admin_user_roles_user_role (admin_user_id, role_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='管理员角色关联表';

-- 角色权限关联表
CREATE TABLE IF NOT EXISTS role_permissions (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID',
  permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_role_permissions_role_permission (role_id, permission_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色权限关联表';

-- -------------------------------------------
-- 系统配置表
-- -------------------------------------------

-- 系统配置表：存储系统级配置项
CREATE TABLE IF NOT EXISTS system_configs (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  `key` VARCHAR(128) NOT NULL COMMENT '配置键',
  `value` TEXT NOT NULL COMMENT '配置值',
  description VARCHAR(255) NOT NULL DEFAULT '' COMMENT '配置说明',
  updated_by BIGINT UNSIGNED NULL COMMENT '更新者ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_system_configs_key (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置表';

-- -------------------------------------------
-- 客服聊天表
-- -------------------------------------------

-- 聊天会话表：订单群聊等
CREATE TABLE IF NOT EXISTS chat_conversations (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NULL COMMENT '关联订单ID',
  type VARCHAR(32) NOT NULL DEFAULT 'order_group' COMMENT '会话类型: order_group订单群聊, support_chat客服咨询',
  title VARCHAR(128) NOT NULL COMMENT '会话标题',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '状态: active活跃, archived已归档, closed已关闭',
  last_message_id BIGINT UNSIGNED NULL COMMENT '最后一条消息ID',
  last_message_preview VARCHAR(255) NOT NULL DEFAULT '' COMMENT '最后消息预览',
  last_message_at DATETIME NULL COMMENT '最后消息时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_chat_conversations_order_id (order_id),
  KEY idx_chat_conversations_last_message_at (last_message_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='聊天会话表';

-- 聊天参与者表：会话成员
CREATE TABLE IF NOT EXISTS chat_participants (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  conversation_id BIGINT UNSIGNED NOT NULL COMMENT '会话ID',
  participant_type VARCHAR(16) NOT NULL COMMENT '参与者类型: user用户, admin管理员',
  participant_id BIGINT UNSIGNED NOT NULL COMMENT '参与者ID',
  role VARCHAR(32) NOT NULL COMMENT '角色: owner号主, renter租客, support客服',
  remark VARCHAR(128) NOT NULL DEFAULT '' COMMENT '备注名',
  last_read_at DATETIME NULL COMMENT '最后已读时间',
  joined_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '加入时间',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_chat_participants_member (conversation_id, participant_type, participant_id),
  KEY idx_chat_participants_participant (participant_type, participant_id),
  KEY idx_chat_participants_conversation (conversation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='聊天参与者表';

-- 聊天消息表：所有聊天消息
CREATE TABLE IF NOT EXISTS chat_messages (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  conversation_id BIGINT UNSIGNED NOT NULL COMMENT '会话ID',
  sender_type VARCHAR(16) NOT NULL COMMENT '发送者类型: user用户, admin管理员, system系统',
  sender_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '发送者ID',
  sender_role VARCHAR(32) NOT NULL DEFAULT '' COMMENT '发送者角色',
  content_type VARCHAR(32) NOT NULL DEFAULT 'text' COMMENT '消息类型: text文本, image图片, file文件',
  content TEXT NULL COMMENT '消息内容',
  attachment_urls JSON NULL COMMENT '附件URL列表',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_chat_messages_conversation_id (conversation_id, id),
  KEY idx_chat_messages_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='聊天消息表';

-- 快捷回复模板表：客服快捷回复
CREATE TABLE IF NOT EXISTS chat_quick_replies (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  admin_user_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '所属管理员ID: 0表示全局模板',
  title VARCHAR(64) NOT NULL COMMENT '快捷回复标题',
  content TEXT NOT NULL COMMENT '回复内容',
  sort_order INT NOT NULL DEFAULT 0 COMMENT '排序权重',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_admin_user_id (admin_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='快捷回复模板表';

-- -------------------------------------------
-- 开放上传记录表
-- -------------------------------------------

-- 商品上传记录表：通过开放接口上传的商品记录
CREATE TABLE IF NOT EXISTS listing_uploads (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  uploader_name VARCHAR(64) NOT NULL COMMENT '上传者名称',
  matched_admin_id BIGINT UNSIGNED NULL COMMENT '匹配到的管理员ID',
  owner_id BIGINT UNSIGNED NULL COMMENT '商品所有者ID',
  client_upload_time DATETIME NULL COMMENT '客户端上传时间',
  client_ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT '客户端IP',
  raw_payload JSON NULL COMMENT '原始请求数据',
  parsed_payload JSON NULL COMMENT '解析后的数据',
  listing_id BIGINT UNSIGNED NULL COMMENT '创建的商品ID',
  status VARCHAR(32) NOT NULL DEFAULT 'draft_created' COMMENT '状态: draft_created草稿已创建, published已发布, failed失败',
  error_message 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,
  KEY idx_listing_uploads_uploader_name (uploader_name),
  KEY idx_listing_uploads_matched_admin_id (matched_admin_id),
  KEY idx_listing_uploads_owner_id (owner_id),
  KEY idx_listing_uploads_listing_id (listing_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品上传记录表';

-- -------------------------------------------
-- 公告系统表
-- -------------------------------------------

-- 公告表：系统公告、通知等
CREATE TABLE IF NOT EXISTS announcements (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(255) NOT NULL COMMENT '公告标题',
  content TEXT NOT NULL COMMENT '公告内容(支持Markdown)',
  category VARCHAR(32) NOT NULL DEFAULT 'notice' COMMENT '分类: notice通知, tutorial教程, rule规则, faq常见问题',
  priority INT NOT NULL DEFAULT 0 COMMENT '优先级(数值越大越靠前)',
  is_pinned TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否置顶: 0否, 1是',
  is_important TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否重要: 0否, 1是',
  view_count INT NOT NULL DEFAULT 0 COMMENT '查看次数',
  status VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT '状态: draft草稿, published已发布, archived已归档',
  published_at DATETIME NULL COMMENT '发布时间',
  created_by BIGINT UNSIGNED NULL COMMENT '创建者ID(管理员)',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_announcements_status (status, is_pinned, priority, published_at),
  KEY idx_announcements_category (category, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='公告表';

SET FOREIGN_KEY_CHECKS = 1;

-- -------------------------------------------
-- 权限数据初始化
-- -------------------------------------------

INSERT INTO permissions (code, name, resource, action) VALUES
('dashboard:view',        '查看仪表盘',       'dashboard',      'view'),
('user:view',             '查看用户',         'user',           'view'),
('user:freeze',           '冻结用户',         'user',           'freeze'),
('user:deposit_free',     '设置免押额度',     'user',           'deposit_free'),
('user:unfreeze',         '解冻用户',         'user',           'unfreeze'),
('order:view',            '查看订单',         'order',          'view'),
('order:close',           '关闭订单',         'order',          'close'),
('order:mark_abnormal',   '标记异常订单',     'order',          'mark_abnormal'),
('listing:view',          '查看商品',         'listing',        'view'),
('listing:approve',       '审核通过商品',     'listing',        'approve'),
('listing:reject',        '审核拒绝商品',     'listing',        'reject'),
('listing:offline',       '下架商品',         'listing',        'offline'),
('dispute:view',          '查看纠纷',         'dispute',        'view'),
('dispute:arbitrate',     '仲裁纠纷',         'dispute',        'arbitrate'),
('chat:view',             '查看客服群聊',     'chat',           'view'),
('chat:send',             '发送客服消息',     'chat',           'send'),
('wallet:view',           '查看资金流水',     'wallet',         'view'),
('wallet:admin_ledger',   '查看资金流水',     'wallet',         'admin_ledger'),
('withdrawal:list',       '查看提现列表',     'withdrawal',     'list'),
('withdrawal:review',     '审核提现',         'withdrawal',     'review'),
('withdrawal:pay',        '确认打款',         'withdrawal',     'pay'),
('withdrawal:detail',     '查看提现详情',     'withdrawal',     'detail'),
('withdrawal:approve',    '提现审核',         'withdrawal',     'approve'),
('payment_config:list',   '查看支付配置',     'payment_config', 'list'),
('payment_config:create', '创建支付配置',     'payment_config', 'create'),
('payment_config:update', '更新支付配置',     'payment_config', 'update'),
('payment_config:delete', '删除支付配置',     'payment_config', 'delete'),
('payment_config:view_secret', '查看支付密钥', 'payment_config', 'view_secret'),
('admin_user:manage',     '管理员管理',       'admin_user',     'manage'),
('role:manage',           '角色管理',         'role',           'manage'),
('system_config:view',    '查看系统配置',     'system_config',  'view'),
('system_config:update',  '修改系统配置',     'system_config',  'update'),
('audit_log:view',        '查看审计日志',     'audit_log',      'view'),
('announcement:view',     '查看公告',         'announcement',   'view'),
('announcement:manage',   '管理公告',         'announcement',   'manage')
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  resource = VALUES(resource),
  action = VALUES(action);

-- -------------------------------------------
-- 角色数据初始化
-- -------------------------------------------

INSERT INTO roles (code, name, description) VALUES
('super_admin', '超级管理员', '拥有所有权限，不可被删除'),
('cs',          '客服',       '处理用户咨询、群聊、纠纷仲裁'),
('ops',         '运营',       '管理商品审核、订单管理、用户管理'),
('finance',     '财务',       '查看资金流水、订单信息')
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  description = VALUES(description);

-- super_admin 拥有所有权限
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r CROSS JOIN permissions p WHERE r.code = 'super_admin';

-- cs 角色权限
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.code = 'cs' AND p.code IN ('dashboard:view', 'user:view', 'dispute:view', 'dispute:arbitrate', 'chat:view', 'chat:send', 'order:view');

-- ops 角色权限
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.code = 'ops' AND p.code IN ('dashboard:view', 'user:view', 'user:freeze', 'user:unfreeze', 'user:deposit_free', 'order:view', 'order:close', 'order:mark_abnormal', 'listing:view', 'listing:approve', 'listing:reject', 'listing:offline', 'dispute:view', 'audit_log:view', 'announcement:view', 'announcement:manage');

-- finance 角色权限
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.code = 'finance' AND p.code IN (
  'dashboard:view',
  'wallet:view',
  'wallet:admin_ledger',
  'order:view',
  'withdrawal:list',
  'withdrawal:review',
  'withdrawal:pay',
  'withdrawal:detail',
  'withdrawal:approve',
  'payment_config:list',
  'payment_config:view_secret'
);

-- -------------------------------------------
-- 管理员账号初始化
-- -------------------------------------------

-- 管理员账号不再由迁移创建，首个超级管理员由启动时的
-- ADMIN_BOOTSTRAP_USERNAME / ADMIN_BOOTSTRAP_PASSWORD 一次性生成。

-- -------------------------------------------
-- 系统配置初始化
-- -------------------------------------------

INSERT INTO system_configs (`key`, `value`, description) VALUES
('listing.review_required', 'true', '商品是否需要审核'),
('order.pending_payment_timeout_minutes', '15', '待支付超时时间（分钟）'),
('chat.default_support_admin_id', '2', '默认客服 ID（必须是启用状态的客服角色）'),
('chat.auto_welcome_message', '欢迎加入订单群聊！如有任何问题，请随时沟通。', '建群后自动发送的欢迎话术')
ON DUPLICATE KEY UPDATE
  `value` = VALUES(`value`),
  description = VALUES(description);

-- -------------------------------------------
-- 公告数据初始化
-- -------------------------------------------

INSERT INTO announcements (title, content, category, priority, is_pinned, is_important, status, published_at) VALUES
('号主须知（重要！）', '## 平台担保交易，拒绝私下转账！

平台提供交易担保机制，用户支付的押金与租金全部冻结在平台账户中，租号结束后根据账号状态自动结算给号主或退款给租客。

**警告：**
- 账号被非本人，请看到此消息后主动下架账号！
- 不要随意更改账号密码或绑定信息
- 请勿诱导买家进行私下交易
- 违规将会被冻结账户并承担相应损失

有任何问题请联系客服处理。', 'notice', 100, 1, 1, 'published', NOW()),

('租客须知（重要！）', '## 账号使用规范

1. **禁止修改账号信息** - 不得修改账号密码、绑定手机、实名信息等
2. **禁止充值** - 租用期间请勿对账号进行任何形式的充值
3. **禁止违规操作** - 不得使用外挂、辅助工具，不得进行恶意行为
4. **按时归还** - 租用到期后请及时归还账号，逾期将扣除押金

**温馨提示：**
- 交接账号后请第一时间登录验证
- 发现账号异常请立即联系客服
- 使用过程中遇到问题随时咨询客服

祝您游戏愉快！', 'notice', 99, 1, 1, 'published', NOW()),

('人脸验证教程', '## 如何完成实名认证

为了保障交易安全，平台要求所有用户完成实名认证后才能发布商品和下单。

### 认证步骤：

1. 进入"个人资料"页面
2. 点击"实名认证"按钮
3. 按照提示填写真实姓名和身份证号
4. 进行人脸识别验证
5. 等待系统审核（通常1-3分钟）

### 注意事项：

- 请确保光线充足，面部清晰
- 摘下眼镜、帽子等遮挡物
- 一个身份证只能认证一个账号
- 认证信息仅用于交易安全，平台严格保密

认证失败请联系客服协助处理。', 'tutorial', 90, 0, 0, 'published', NOW()),

('除纯市外其他高级物资默认从收费表', '## 出租开始须必开启备锁！

号主在出租账号前，务必确保账号已开启"账号保护"功能（即备锁）。

### 为什么要开启备锁？

- 防止租客恶意修改账号信息
- 保护账号安全，降低被盗风险
- 发生纠纷时便于平台介入处理
- 租用结束后方便号主快速收回账号

### 如何开启？

具体开启方式请参考游戏官方设置，不同平台操作略有差异。如不清楚如何设置，请咨询客服。

**重要提醒：未开启备锁导致的账号安全问题，平台不承担责任！**', 'rule', 80, 0, 0, 'published', NOW()),

('出租完成后如何结算？', '## 租金结算流程

租用期满后，系统会根据账号状态自动进行结算：

### 正常归还
- 租客按时归还账号
- 号主确认账号无异常
- 系统自动将租金结算到号主钱包
- 押金退还给租客

### 异常情况
- 账号信息被修改 → 押金赔付给号主
- 账号被找回 → 租金退还给租客
- 产生纠纷 → 平台客服介入仲裁

### 提现说明
目前提现功能暂未开放，敬请期待后续更新。', 'faq', 70, 0, 0, 'published', NOW()),

('如何联系客服？', '## 客服联系方式

遇到问题可以通过以下方式联系客服：

1. **在线客服** - 点击页面右上角"客服"按钮，即可在线咨询
2. **订单页面** - 每个订单详情页都有专属客服入口
3. **消息中心** - 查看历史咨询记录

### 客服工作时间
- 工作日：09:00 - 22:00
- 节假日：10:00 - 20:00

非工作时间留言，客服上线后会第一时间回复。', 'faq', 60, 0, 0, 'published', NOW());

-- -------------------------------------------
-- 用户收款账号表（提现功能）
-- -------------------------------------------

CREATE TABLE IF NOT EXISTS user_payment_accounts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  account_type VARCHAR(32) NOT NULL COMMENT '账号类型: alipay支付宝, wechat微信, bank银行卡',
  account_name VARCHAR(128) NOT NULL COMMENT '账户名（真实姓名）',
  account_no VARCHAR(255) NOT NULL COMMENT '账号（加密存储）',

  -- 银行卡专用字段
  bank_name VARCHAR(128) NOT NULL DEFAULT '' COMMENT '银行名称',
  bank_branch VARCHAR(255) NOT NULL DEFAULT '' COMMENT '开户行支行',

  -- 凭证
  certificate_urls JSON NULL COMMENT '认证凭证（收款码截图等）',

  is_default TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否默认账号',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '状态: active正常, disabled禁用',

  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  KEY idx_user_payment_accounts_user_id (user_id),
  KEY idx_user_payment_accounts_user_default (user_id, is_default)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户收款账号表';

-- -------------------------------------------
-- 提现申请表
-- -------------------------------------------

CREATE TABLE IF NOT EXISTS withdrawal_requests (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  withdraw_no VARCHAR(64) NOT NULL COMMENT '提现单号',
  user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
  amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '提现金额(分)',
  fee_cent BIGINT NOT NULL DEFAULT 0 COMMENT '手续费(分)',
  actual_amount_cent BIGINT NOT NULL DEFAULT 0 COMMENT '实际到账(分)',

  -- 收款账号信息（快照）
  payment_account_id BIGINT UNSIGNED NULL COMMENT '收款账号ID',
  account_type VARCHAR(32) NOT NULL COMMENT '账号类型',
  account_name VARCHAR(128) NOT NULL COMMENT '账户名',
  account_no VARCHAR(128) NOT NULL COMMENT '账号（脱敏显示）',
  bank_name VARCHAR(128) NOT NULL DEFAULT '' COMMENT '银行名称',
  bank_branch VARCHAR(255) NOT NULL DEFAULT '' COMMENT '开户行支行',

  status VARCHAR(32) NOT NULL DEFAULT 'pending' COMMENT '状态: pending待审核, processing处理中, completed已完成, rejected已拒绝, cancelled已取消',

  -- 审核信息
  reviewed_by BIGINT UNSIGNED NULL COMMENT '审核人ID（财务管理员）',
  reviewed_at DATETIME NULL COMMENT '审核时间',
  review_remark VARCHAR(255) NOT NULL DEFAULT '' COMMENT '审核备注',

  -- 打款信息
  paid_by BIGINT UNSIGNED NULL COMMENT '打款人ID（财务管理员）',
  paid_at DATETIME NULL COMMENT '打款时间',
  payment_proof_url VARCHAR(512) NOT NULL DEFAULT '' COMMENT '打款凭证URL',
  payment_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_withdrawal_requests_withdraw_no (withdraw_no),
  KEY idx_withdrawal_requests_user_id (user_id),
  KEY idx_withdrawal_requests_status (status),
  KEY idx_withdrawal_requests_created (created_at DESC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='提现申请表';

-- 确保超级管理员包含所有已初始化权限
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r
CROSS JOIN permissions p
WHERE r.code = 'super_admin';

-- 确保财务角色包含提现和支付配置权限
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM roles r, permissions p
WHERE r.code = 'finance' AND p.code IN (
  'withdrawal:list',
  'withdrawal:review',
  'withdrawal:pay',
  'withdrawal:detail',
  'withdrawal:approve',
  'wallet:admin_ledger',
  'payment_config:list',
  'payment_config:view_secret'
);

-- ============================================
-- 数据库初始化完成
-- ============================================
