-- ============================================================================
-- Crawlful Hub 数据库初始化脚本
-- Task ID: OP-DE003
-- Description: 创建所有业务表结构
-- Database: MySQL 8.0
-- Table Prefix: cf_ (Crawlful)
-- ============================================================================

-- 设置字符集
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ============================================================================
-- 1. 租户与用户管理表
-- ============================================================================

-- 租户表
CREATE TABLE IF NOT EXISTS `cf_tenants` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '租户ID',
    `name` VARCHAR(255) NOT NULL COMMENT '租户名称',
    `status` ENUM('ACTIVE', 'SUSPENDED', 'DELETED') DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE-活跃，SUSPENDED-暂停，DELETED-已删除',
    `plan` ENUM('FREE', 'BASIC', 'PRO', 'ENTERPRISE') DEFAULT 'BASIC' COMMENT '套餐类型：FREE-免费，BASIC-基础，PRO-专业，ENTERPRISE-企业',
    `settings` JSON COMMENT '租户配置信息',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_status` (`status`),
    INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='租户信息表';

-- 用户表
CREATE TABLE IF NOT EXISTS `cf_users` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '用户ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `username` VARCHAR(100) NOT NULL COMMENT '用户名',
    `email` VARCHAR(255) NOT NULL COMMENT '邮箱',
    `password_hash` VARCHAR(255) NOT NULL COMMENT '密码哈希值',
    `role` ENUM('ADMIN', 'MANAGER', 'OPERATOR', 'FINANCE', 'SOURCING', 'LOGISTICS', 'ANALYST') DEFAULT 'OPERATOR' COMMENT '角色：ADMIN-管理员，MANAGER-经理，OPERATOR-操作员，FINANCE-财务，SOURCING-采购，LOGISTICS-物流，ANALYST-分析师',
    `status` ENUM('ACTIVE', 'INACTIVE', 'SUSPENDED') DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE-活跃，INACTIVE-未激活，SUSPENDED-暂停',
    `last_login_at` TIMESTAMP NULL COMMENT '最后登录时间',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY `uk_tenant_email` (`tenant_id`, `email`),
    UNIQUE KEY `uk_tenant_username` (`tenant_id`, `username`),
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_status` (`status`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户信息表';

-- ============================================================================
-- 2. 商品管理表
-- ============================================================================

-- 商品主表
CREATE TABLE IF NOT EXISTS `cf_product` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '商品ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `platform` VARCHAR(50) NOT NULL COMMENT '平台名称',
    `product_id` VARCHAR(255) NOT NULL COMMENT '平台商品ID',
    `sku` VARCHAR(255) COMMENT 'SKU编码',
    `name` VARCHAR(500) NOT NULL COMMENT '商品名称',
    `description` TEXT COMMENT '商品描述',
    `category` VARCHAR(255) COMMENT '商品分类',
    `brand` VARCHAR(255) COMMENT '品牌',
    `images` JSON COMMENT '商品图片列表',
    `attributes` JSON COMMENT '商品属性',
    `status` ENUM('DRAFT', 'ACTIVE', 'INACTIVE', 'DELETED') DEFAULT 'DRAFT' COMMENT '状态：DRAFT-草稿，ACTIVE-活跃，INACTIVE-未激活，DELETED-已删除',
    `cost_price` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '成本价',
    `selling_price` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '销售价',
    `currency` VARCHAR(10) DEFAULT 'USD' COMMENT '货币类型',
    `weight` DECIMAL(10, 3) COMMENT '重量',
    `weight_unit` VARCHAR(10) DEFAULT 'kg' COMMENT '重量单位',
    `length` DECIMAL(10, 2) COMMENT '长度',
    `width` DECIMAL(10, 2) COMMENT '宽度',
    `height` DECIMAL(10, 2) COMMENT '高度',
    `dimension_unit` VARCHAR(10) DEFAULT 'cm' COMMENT '尺寸单位',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `task_id` VARCHAR(64) COMMENT '任务ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY `uk_platform_product` (`platform`, `product_id`),
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_shop_id` (`shop_id`),
    INDEX `idx_status` (`status`),
    INDEX `idx_category` (`category`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品主表';

-- SKU 变体表
CREATE TABLE IF NOT EXISTS `cf_product_sku` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT 'SKU ID',
    `product_id` VARCHAR(64) NOT NULL COMMENT '商品ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `sku_code` VARCHAR(255) NOT NULL COMMENT 'SKU编码',
    `variant_attributes` JSON COMMENT '变体属性',
    `cost_price` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '成本价',
    `selling_price` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '销售价',
    `stock_quantity` INT DEFAULT 0 COMMENT '库存数量',
    `status` ENUM('ACTIVE', 'INACTIVE') DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE-活跃，INACTIVE-未激活',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY `uk_product_sku` (`product_id`, `sku_code`),
    INDEX `idx_tenant_id` (`tenant_id`),
    FOREIGN KEY (`product_id`) REFERENCES `cf_product`(`id`) ON DELETE CASCADE,
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='SKU变体表';

-- ============================================================================
-- 3. 订单管理表
-- ============================================================================

-- 订单主表
CREATE TABLE IF NOT EXISTS `cf_orders` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '订单ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `platform` VARCHAR(50) NOT NULL COMMENT '平台名称',
    `platform_order_id` VARCHAR(255) COMMENT '平台订单ID',
    `customer_id` VARCHAR(64) COMMENT '客户ID',
    `status` ENUM('PENDING', 'PAID', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'COMPLETED', 'CANCELLED', 'REFUNDED') DEFAULT 'PENDING' COMMENT '状态：PENDING-待处理，PAID-已支付，PROCESSING-处理中，SHIPPED-已发货，DELIVERED-已送达，COMPLETED-已完成，CANCELLED-已取消，REFUNDED-已退款',
    `items` JSON COMMENT '订单商品列表',
    `subtotal` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '小计金额',
    `shipping_fee` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '运费',
    `tax` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '税费',
    `discount` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '折扣金额',
    `total_amount` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '总金额',
    `currency` VARCHAR(10) DEFAULT 'USD' COMMENT '货币类型',
    `shipping_address` JSON COMMENT '收货地址',
    `billing_address` JSON COMMENT '账单地址',
    `payment_method` VARCHAR(50) COMMENT '支付方式',
    `payment_status` ENUM('PENDING', 'PAID', 'FAILED', 'REFUNDED') DEFAULT 'PENDING' COMMENT '支付状态：PENDING-待支付，PAID-已支付，FAILED-失败，REFUNDED-已退款',
    `delivered_at` TIMESTAMP NULL COMMENT '送达时间',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `task_id` VARCHAR(64) COMMENT '任务ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_shop_id` (`shop_id`),
    INDEX `idx_platform_order` (`platform`, `platform_order_id`),
    INDEX `idx_status` (`status`),
    INDEX `idx_customer_id` (`customer_id`),
    INDEX `idx_created_at` (`created_at`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单主表';

-- ============================================================================
-- 4. 财务管理表
-- ============================================================================

-- 对账记录表
CREATE TABLE IF NOT EXISTS `cf_reconciliation` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '对账记录ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `platform` VARCHAR(50) NOT NULL COMMENT '平台名称',
    `period_start` DATE NOT NULL COMMENT '对账开始日期',
    `period_end` DATE NOT NULL COMMENT '对账结束日期',
    `expected_amount` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '预期金额',
    `actual_amount` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '实际金额',
    `difference` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '差异金额',
    `status` ENUM('PENDING', 'MATCHED', 'MISMATCH', 'RESOLVED') DEFAULT 'PENDING' COMMENT '状态：PENDING-待处理，MATCHED-匹配，MISMATCH-不匹配，RESOLVED-已解决',
    `details` JSON COMMENT '对账详情',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_platform_period` (`platform`, `period_start`, `period_end`),
    INDEX `idx_status` (`status`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='对账记录表';

-- 回款记录表
CREATE TABLE IF NOT EXISTS `cf_payments` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '回款记录ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `order_id` VARCHAR(64) COMMENT '订单ID',
    `platform` VARCHAR(50) COMMENT '平台名称',
    `amount` DECIMAL(12, 2) NOT NULL COMMENT '回款金额',
    `currency` VARCHAR(10) DEFAULT 'USD' COMMENT '货币类型',
    `status` ENUM('PENDING', 'PROCESSING', 'COMPLETED', 'FAILED', 'REFUNDED') DEFAULT 'PENDING' COMMENT '状态：PENDING-待处理，PROCESSING-处理中，COMPLETED-已完成，FAILED-失败，REFUNDED-已退款',
    `payment_method` VARCHAR(50) COMMENT '支付方式',
    `transaction_id` VARCHAR(255) COMMENT '交易ID',
    `paid_at` TIMESTAMP NULL COMMENT '支付时间',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `task_id` VARCHAR(64) COMMENT '任务ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_order_id` (`order_id`),
    INDEX `idx_status` (`status`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='回款记录表';

-- ============================================================================
-- 5. B2B 贸易管理表
-- ============================================================================

-- B2B 客户表
CREATE TABLE IF NOT EXISTS `cf_b2b_customers` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '客户ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `company_name` VARCHAR(255) NOT NULL COMMENT '公司名称',
    `contact_name` VARCHAR(255) COMMENT '联系人姓名',
    `contact_email` VARCHAR(255) COMMENT '联系人邮箱',
    `contact_phone` VARCHAR(50) COMMENT '联系人电话',
    `credit_limit` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '信用额度',
    `credit_used` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '已用信用额度',
    `payment_terms` INT DEFAULT 30 COMMENT '账期天数',
    `tier_level` ENUM('BRONZE', 'SILVER', 'GOLD', 'PLATINUM') DEFAULT 'BRONZE' COMMENT '等级：BRONZE-青铜，SILVER-白银，GOLD-黄金，PLATINUM-白金',
    `status` ENUM('ACTIVE', 'INACTIVE', 'SUSPENDED') DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE-活跃，INACTIVE-未激活，SUSPENDED-暂停',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_tier_level` (`tier_level`),
    INDEX `idx_status` (`status`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='B2B客户表';

-- 阶梯价格表
CREATE TABLE IF NOT EXISTS `cf_tiered_prices` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '阶梯价格ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `product_id` VARCHAR(64) NOT NULL COMMENT '商品ID',
    `min_quantity` INT NOT NULL COMMENT '最小数量',
    `max_quantity` INT COMMENT '最大数量',
    `price` DECIMAL(12, 2) NOT NULL COMMENT '价格',
    `discount_percent` DECIMAL(5, 2) DEFAULT 0.00 COMMENT '折扣百分比',
    `status` ENUM('ACTIVE', 'INACTIVE') DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE-活跃，INACTIVE-未激活',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_product` (`tenant_id`, `product_id`),
    INDEX `idx_quantity_range` (`min_quantity`, `max_quantity`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE,
    FOREIGN KEY (`product_id`) REFERENCES `cf_product`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='阶梯价格表';

-- ============================================================================
-- 6. 售后管理表
-- ============================================================================

-- 退货申请表
CREATE TABLE IF NOT EXISTS `cf_return_requests` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '退货申请ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `order_id` VARCHAR(64) NOT NULL COMMENT '订单ID',
    `status` ENUM('PENDING', 'APPROVED', 'REJECTED', 'RETURNED', 'REFUNDED', 'CLOSED') DEFAULT 'PENDING' COMMENT '状态：PENDING-待处理，APPROVED-已批准，REJECTED-已拒绝，RETURNED-已退货，REFUNDED-已退款，CLOSED-已关闭',
    `reason` TEXT COMMENT '退货原因',
    `items` JSON COMMENT '退货商品列表',
    `total_refund_amount` DECIMAL(12, 2) DEFAULT 0.00 COMMENT '总退款金额',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `task_id` VARCHAR(64) COMMENT '任务ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_order_id` (`order_id`),
    INDEX `idx_status` (`status`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='退货申请表';

-- 退款记录表
CREATE TABLE IF NOT EXISTS `cf_refunds` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '退款记录ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `return_id` VARCHAR(64) NOT NULL COMMENT '退货申请ID',
    `order_id` VARCHAR(64) NOT NULL COMMENT '订单ID',
    `amount` DECIMAL(12, 2) NOT NULL COMMENT '退款金额',
    `status` ENUM('PENDING_REVIEW', 'APPROVED', 'PROCESSING', 'COMPLETED', 'FAILED', 'CANCELLED') DEFAULT 'PENDING_REVIEW' COMMENT '状态：PENDING_REVIEW-待审核，APPROVED-已批准，PROCESSING-处理中，COMPLETED-已完成，FAILED-失败，CANCELLED-已取消',
    `method` VARCHAR(50) DEFAULT 'ORIGINAL_PAYMENT' COMMENT '退款方式',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `task_id` VARCHAR(64) COMMENT '任务ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_return_id` (`return_id`),
    INDEX `idx_order_id` (`order_id`),
    INDEX `idx_status` (`status`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='退款记录表';

-- 售后工单表
CREATE TABLE IF NOT EXISTS `cf_service_tickets` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '工单ID',
    `tenant_id` VARCHAR(64) NOT NULL COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `return_id` VARCHAR(64) COMMENT '退货申请ID',
    `type` ENUM('RETURN', 'REFUND', 'EXCHANGE', 'COMPLAINT', 'INQUIRY') DEFAULT 'INQUIRY' COMMENT '类型：RETURN-退货，REFUND-退款，EXCHANGE-换货，COMPLAINT-投诉，INQUIRY-咨询',
    `priority` ENUM('LOW', 'MEDIUM', 'HIGH', 'URGENT') DEFAULT 'MEDIUM' COMMENT '优先级：LOW-低，MEDIUM-中，HIGH-高，URGENT-紧急',
    `status` ENUM('OPEN', 'IN_PROGRESS', 'WAITING_CUSTOMER', 'WAITING_INTERNAL', 'RESOLVED', 'CLOSED') DEFAULT 'OPEN' COMMENT '状态：OPEN-已开启，IN_PROGRESS-处理中，WAITING_CUSTOMER-等待客户，WAITING_INTERNAL-等待内部，RESOLVED-已解决，CLOSED-已关闭',
    `subject` VARCHAR(255) COMMENT '工单主题',
    `description` TEXT COMMENT '工单描述',
    `messages` JSON COMMENT '工单消息列表',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `task_id` VARCHAR(64) COMMENT '任务ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_return_id` (`return_id`),
    INDEX `idx_status` (`status`),
    INDEX `idx_priority` (`priority`),
    FOREIGN KEY (`tenant_id`) REFERENCES `cf_tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='售后工单表';

-- ============================================================================
-- 7. 审计日志表
-- ============================================================================

-- 操作审计表
CREATE TABLE IF NOT EXISTS `cf_audit_logs` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '审计日志ID',
    `tenant_id` VARCHAR(64) COMMENT '租户ID',
    `user_id` VARCHAR(64) COMMENT '用户ID',
    `action` VARCHAR(100) NOT NULL COMMENT '操作类型',
    `entity_type` VARCHAR(100) COMMENT '实体类型',
    `entity_id` VARCHAR(64) COMMENT '实体ID',
    `old_value` JSON COMMENT '旧值',
    `new_value` JSON COMMENT '新值',
    `ip_address` VARCHAR(45) COMMENT 'IP地址',
    `user_agent` VARCHAR(500) COMMENT '用户代理',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_user_id` (`user_id`),
    INDEX `idx_action` (`action`),
    INDEX `idx_entity` (`entity_type`, `entity_id`),
    INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作审计表';

-- ============================================================================
-- 8. 任务追踪表
-- ============================================================================

-- 任务执行记录表
CREATE TABLE IF NOT EXISTS `cf_task_executions` (
    `id` VARCHAR(64) PRIMARY KEY COMMENT '任务执行ID',
    `tenant_id` VARCHAR(64) COMMENT '租户ID',
    `shop_id` VARCHAR(64) COMMENT '店铺ID',
    `task_id` VARCHAR(64) NOT NULL COMMENT '任务ID',
    `task_type` VARCHAR(100) NOT NULL COMMENT '任务类型',
    `status` ENUM('PENDING', 'RUNNING', 'COMPLETED', 'FAILED', 'CANCELLED') DEFAULT 'PENDING' COMMENT '状态：PENDING-待处理，RUNNING-运行中，COMPLETED-已完成，FAILED-失败，CANCELLED-已取消',
    `input` JSON COMMENT '输入参数',
    `output` JSON COMMENT '输出结果',
    `error_message` TEXT COMMENT '错误信息',
    `retry_count` INT DEFAULT 0 COMMENT '重试次数',
    `started_at` TIMESTAMP NULL COMMENT '开始时间',
    `completed_at` TIMESTAMP NULL COMMENT '完成时间',
    `trace_id` VARCHAR(64) COMMENT '追踪ID',
    `business_type` ENUM('TOC', 'TOB') DEFAULT 'TOC' COMMENT '业务类型：TOC-对客，TOB-对企业',
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_tenant_id` (`tenant_id`),
    INDEX `idx_task_id` (`task_id`),
    INDEX `idx_task_type` (`task_type`),
    INDEX `idx_status` (`status`),
    INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='任务执行记录表';

-- ============================================================================
-- 完成提示
-- ============================================================================

SET FOREIGN_KEY_CHECKS = 1;

-- 显示创建结果
SELECT 'Database initialization completed!' AS message;
SELECT COUNT(*) AS table_count FROM information_schema.tables 
WHERE table_schema = DATABASE() AND table_name LIKE 'cf_%';
