-- ============================================
-- 数据库初始化脚本
-- 包含所有表结构和基础数据
-- ============================================

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,
  nickname VARCHAR(64) NOT NULL DEFAULT '',
  avatar_url VARCHAR(512) NOT NULL DEFAULT '',
  realname_status VARCHAR(32) NOT NULL DEFAULT 'unverified',
  risk_status VARCHAR(32) NOT NULL DEFAULT 'normal',
  credit_score INT NOT NULL DEFAULT 100,
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  last_login_at DATETIME NULL,
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS user_realname (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL,
  provider VARCHAR(32) NOT NULL,
  provider_order_no VARCHAR(128) NOT NULL DEFAULT '',
  status VARCHAR(32) NOT NULL DEFAULT 'pending',
  masked_name VARCHAR(64) NOT NULL DEFAULT '',
  masked_id_no VARCHAR(64) NOT NULL DEFAULT '',
  verified_at DATETIME NULL,
  fail_reason VARCHAR(255) NOT NULL DEFAULT '',
  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;

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

CREATE TABLE IF NOT EXISTS game_accounts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  owner_id BIGINT UNSIGNED NOT NULL,
  game_name VARCHAR(64) NOT NULL DEFAULT 'delta_force',
  server_region VARCHAR(64) NOT NULL,
  login_platform VARCHAR(64) NOT NULL,
  title VARCHAR(128) NOT NULL,
  description TEXT NULL,
  rank_level VARCHAR(64) NOT NULL DEFAULT '',
  haf_coin_amount BIGINT NOT NULL DEFAULT 0,
  asset_summary JSON NULL,
  season_tags JSON NULL,
  screenshot_urls JSON NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'draft',
  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;

CREATE TABLE IF NOT EXISTS rental_listings (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  account_id BIGINT UNSIGNED NOT NULL,
  owner_id BIGINT UNSIGNED NOT NULL,
  price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  deposit_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  in_transaction TINYINT(1) NOT NULL DEFAULT 0,
  status VARCHAR(32) NOT NULL DEFAULT 'draft',
  review_status VARCHAR(32) NOT NULL DEFAULT 'none',
  review_reason VARCHAR(255) NOT NULL DEFAULT '',
  published_at DATETIME NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

CREATE TABLE IF NOT EXISTS rental_orders (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_no VARCHAR(64) NOT NULL,
  listing_id BIGINT UNSIGNED NOT NULL,
  account_id BIGINT UNSIGNED NOT NULL,
  owner_id BIGINT UNSIGNED NOT NULL,
  renter_id BIGINT UNSIGNED NOT NULL,
  rented_at DATETIME NULL,
  estimated_duration_hours INT NOT NULL DEFAULT 24,
  rent_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  owner_rent_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  deposit_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  platform_fee DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  account_snapshot JSON NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'pending_payment',
  handoff_status VARCHAR(32) NOT NULL DEFAULT 'none',
  settlement_status VARCHAR(32) NOT NULL DEFAULT 'unsettled',
  refund_status VARCHAR(32) NOT NULL DEFAULT 'none',
  refund_amount_cent BIGINT NOT NULL DEFAULT 0,
  refunded_at DATETIME NULL,
  owner_settled_at DATETIME NULL,
  settled_at DATETIME NULL,
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS order_checkouts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL,
  initiated_by BIGINT UNSIGNED NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'submitted',
  rent_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  owner_rent_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  platform_fee DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  deposit_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  consumable_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  coin_consumed_m DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  other_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  deposit_deduct_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  renter_refund_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  owner_income_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  content TEXT NULL,
  evidence_urls JSON NULL,
  owner_adjustment_reason TEXT NULL,
  owner_adjusted_at DATETIME NULL,
  renter_confirmed_at DATETIME NULL,
  renter_rejected_at DATETIME NULL,
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS handoff_records (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL,
  from_user_id BIGINT UNSIGNED NOT NULL,
  to_user_id BIGINT UNSIGNED NOT NULL,
  type VARCHAR(32) NOT NULL,
  content TEXT NULL,
  attachment_urls JSON NULL,
  confirmed_by_renter_at DATETIME NULL,
  confirmed_by_owner_at DATETIME NULL,
  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;

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

CREATE TABLE IF NOT EXISTS wallet_accounts (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL,
  available_balance DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  frozen_balance DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  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;

CREATE TABLE IF NOT EXISTS wallet_ledger (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  ledger_no VARCHAR(64) NOT NULL,
  user_id BIGINT UNSIGNED NOT NULL,
  order_id BIGINT UNSIGNED NULL,
  direction VARCHAR(16) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  balance_after DECIMAL(12,2) NOT NULL,
  balance_type VARCHAR(32) NOT NULL,
  biz_type VARCHAR(32) NOT NULL,
  biz_no VARCHAR(64) NOT NULL,
  remark VARCHAR(255) NOT NULL DEFAULT '',
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

CREATE TABLE IF NOT EXISTS payment_orders (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  payment_no VARCHAR(64) NOT NULL,
  order_id BIGINT UNSIGNED NOT NULL,
  order_no VARCHAR(64) NOT NULL,
  user_id BIGINT UNSIGNED NOT NULL,
  provider VARCHAR(32) NOT NULL,
  merchant_id VARCHAR(32) NOT NULL DEFAULT '',
  third_order_id VARCHAR(64) NOT NULL,
  provider_order_id VARCHAR(64) NOT NULL DEFAULT '',
  pay_way VARCHAR(16) NOT NULL DEFAULT '',
  jspay_flag VARCHAR(8) NOT NULL DEFAULT '',
  amount_cent BIGINT NOT NULL DEFAULT 0,
  biz_type VARCHAR(32) NOT NULL DEFAULT 'order_pay',
  status VARCHAR(32) NOT NULL DEFAULT 'created',
  td_code VARCHAR(512) NOT NULL DEFAULT '',
  jspay_url VARCHAR(512) NOT NULL DEFAULT '',
  jspay_info TEXT NULL,
  raw_request JSON NULL,
  raw_response JSON NULL,
  paid_at DATETIME NULL,
  notified_at DATETIME NULL,
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

CREATE TABLE IF NOT EXISTS disputes (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NOT NULL,
  initiator_id BIGINT UNSIGNED NOT NULL,
  target_user_id BIGINT UNSIGNED NOT NULL,
  type VARCHAR(32) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'open',
  description TEXT NULL,
  evidence_urls JSON NULL,
  arbitration_result VARCHAR(32) NOT NULL DEFAULT '',
  arbitration_remark TEXT NULL,
  handled_by BIGINT UNSIGNED NULL,
  handled_at DATETIME NULL,
  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;

CREATE TABLE IF NOT EXISTS notifications (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT UNSIGNED NOT NULL,
  type VARCHAR(32) NOT NULL,
  title VARCHAR(128) NOT NULL,
  content TEXT NULL,
  biz_type VARCHAR(32) NOT NULL DEFAULT '',
  biz_id BIGINT UNSIGNED NULL,
  read_at DATETIME NULL,
  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;

CREATE TABLE IF NOT EXISTS audit_logs (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  actor_type VARCHAR(32) NOT NULL,
  actor_id BIGINT UNSIGNED NOT NULL,
  action VARCHAR(64) NOT NULL,
  biz_type VARCHAR(32) NOT NULL,
  biz_id BIGINT UNSIGNED NULL,
  ip VARCHAR(64) NOT NULL DEFAULT '',
  user_agent VARCHAR(512) NOT NULL DEFAULT '',
  detail JSON NULL,
  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;

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

CREATE TABLE IF NOT EXISTS admin_users (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  username VARCHAR(64) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  nickname VARCHAR(64) NOT NULL DEFAULT '',
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  last_login_at DATETIME NULL,
  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)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS roles (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  code VARCHAR(64) NOT NULL,
  name VARCHAR(64) NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  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;

CREATE TABLE IF NOT EXISTS permissions (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  code VARCHAR(128) NOT NULL,
  name VARCHAR(64) NOT NULL,
  resource VARCHAR(128) NOT NULL,
  action VARCHAR(64) NOT NULL,
  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;

CREATE TABLE IF NOT EXISTS admin_user_roles (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  admin_user_id BIGINT UNSIGNED NOT NULL,
  role_id BIGINT UNSIGNED NOT NULL,
  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;

CREATE TABLE IF NOT EXISTS role_permissions (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  role_id BIGINT UNSIGNED NOT NULL,
  permission_id BIGINT UNSIGNED NOT NULL,
  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;

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

CREATE TABLE IF NOT EXISTS system_configs (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  `key` VARCHAR(128) NOT NULL,
  `value` TEXT NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  updated_by BIGINT UNSIGNED NULL,
  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;

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

CREATE TABLE IF NOT EXISTS chat_conversations (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT UNSIGNED NULL,
  type VARCHAR(32) NOT NULL DEFAULT 'order_group',
  title VARCHAR(128) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'active',
  last_message_id BIGINT UNSIGNED NULL,
  last_message_preview VARCHAR(255) NOT NULL DEFAULT '',
  last_message_at DATETIME NULL,
  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;

CREATE TABLE IF NOT EXISTS chat_participants (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  conversation_id BIGINT UNSIGNED NOT NULL,
  participant_type VARCHAR(16) NOT NULL,
  participant_id BIGINT UNSIGNED NOT NULL,
  role VARCHAR(32) NOT NULL,
  remark VARCHAR(128) NOT NULL DEFAULT '',
  last_read_at DATETIME NULL,
  joined_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  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;

CREATE TABLE IF NOT EXISTS chat_messages (
  id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  conversation_id BIGINT UNSIGNED NOT NULL,
  sender_type VARCHAR(16) NOT NULL,
  sender_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
  sender_role VARCHAR(32) NOT NULL DEFAULT '',
  content_type VARCHAR(32) NOT NULL DEFAULT 'text',
  content TEXT NULL,
  attachment_urls JSON NULL,
  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;

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 '0=全局, >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,
  INDEX 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,
  matched_admin_id BIGINT UNSIGNED NULL,
  owner_id BIGINT UNSIGNED NULL,
  client_upload_time DATETIME NULL,
  client_ip VARCHAR(64) NOT NULL DEFAULT '',
  raw_payload JSON NULL,
  parsed_payload JSON NULL,
  listing_id BIGINT UNSIGNED NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'draft_created',
  error_message VARCHAR(255) NOT NULL DEFAULT '',
  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;

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: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'),
('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')
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', 'order:view', 'order:close', 'order:mark_abnormal', 'listing:view', 'listing:approve', 'listing:reject', 'listing:offline', 'dispute:view', 'audit_log:view');

-- 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', 'order:view');

-- -------------------------------------------
-- 管理员账号
-- -------------------------------------------

-- 生成 admin 密码 hash: admin123456
INSERT INTO admin_users (username, password_hash, nickname, status) VALUES
('admin', '$2a$10$vvDd.cYJCOBl9kr5jdRYXu9C/7GXcHmXsG17zJPHzPOZ0XGbqcWNS', '超级管理员', 'active'),
('kf1', '$2a$10$7cx3B4IWunLZO24o11YVGu4qY1J1naDdsTyvoCpcnOO.GV15qaf3C', '客服1', 'active'),
('kf2', '$2a$10$m6kLCXciFygpqIGUZ9LQtuEFAl40hb.S7zJmMiuC83WrU7OQM3TPC', '客服2', 'active')
ON DUPLICATE KEY UPDATE
  nickname = VALUES(nickname),
  status = VALUES(status);

-- admin 关联 super_admin 角色
INSERT IGNORE INTO admin_user_roles (admin_user_id, role_id)
SELECT au.id, r.id FROM admin_users au, roles r
WHERE au.username = 'admin' AND r.code = 'super_admin';

-- 客服关联 cs 角色
INSERT IGNORE INTO admin_user_roles (admin_user_id, role_id)
SELECT au.id, r.id FROM admin_users au, roles r
WHERE au.username IN ('kf1', 'kf2') AND r.code = 'cs';

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

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