import db from '../../config/database';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '../../utils/logger';
import { AuditService } from '../core/AuditService';
import { ComplianceRule } from '../../models/ComplianceRule';
import { SecurityConfig, SecurityStatus, ComplianceCheck as SecurityComplianceCheck, ComplianceResult } from '../../types/security';

export interface ComplianceCheck {
  id: string;
  tenantId: string;
  shopId: string;
  productId: string;
  platform: string;
  status: 'COMPLIANT' | 'NON_COMPLIANT' | 'PENDING';
  issues: string[];
  checkedAt: Date;
  updatedAt: Date;
}

export interface PolicyMonitor {
  id: string;
  tenantId: string;
  platform: string;
  policyId: string;
  policyName: string;
  changeType: 'NEW' | 'UPDATED' | 'DELETED';
  effectiveDate: Date;
  status: 'PENDING' | 'PROCESSED' | 'IGNORED';
  createdAt: Date;
  updatedAt: Date;
}

export interface ComplianceRisk {
  id: string;
  tenantId: string;
  shopId: string;
  riskType: string;
  severity: 'LOW' | 'MEDIUM' | 'HIGH';
  status: 'ACTIVE' | 'MITIGATED' | 'RESOLVED';
  description: string;
  mitigationPlan: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface DataCompliance {
  id: string;
  tenantId: string;
  dataType: string;
  complianceStatus: 'COMPLIANT' | 'NON_COMPLIANT' | 'PENDING';
  lastChecked: Date;
  updatedAt: Date;
}

export interface TaxCompliance {
  id: string;
  tenantId: string;
  shopId: string;
  taxType: string;
  status: 'COMPLIANT' | 'NON_COMPLIANT' | 'PENDING';
  filingDate: Date;
  dueDate: Date;
  amount: number;
  currency: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface SecurityCompliance {
  id: string;
  tenantId: string;
  securityType: string;
  status: 'COMPLIANT' | 'NON_COMPLIANT' | 'PENDING';
  lastScanned: Date;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
  remediationSteps: string[];
  createdAt: Date;
  updatedAt: Date;
}

export class ComplianceService {
  private static readonly TABLE_COMPLIANCE_CHECK = 'cf_compliance_checks';
  private static readonly TABLE_POLICY_MONITOR = 'cf_policy_monitors';
  private static readonly TABLE_COMPLIANCE_RISK = 'cf_compliance_risks';
  private static readonly TABLE_DATA_COMPLIANCE = 'cf_data_compliance';
  private static readonly TABLE_COMPLIANCE_RULE = 'cf_compliance_rules';
  private static readonly TABLE_TAX_COMPLIANCE = 'cf_tax_compliance';
  private static readonly TABLE_SECURITY_COMPLIANCE = 'cf_security_compliance';
  private static readonly TABLE_INVENTORY_SYNC_LOGS = 'cf_inventory_sync_logs';
  
  // 内存存储（用于安全配置和合规检查）
  private static securityConfigs: Map<string, SecurityConfig> = new Map();
  private static securityStatus: Map<string, SecurityStatus> = new Map();
  private static complianceChecks: Map<string, SecurityComplianceCheck> = new Map();

  // ==================== 合规检查 ====================

  static async createComplianceCheck(checkData: Partial<ComplianceCheck>): Promise<ComplianceCheck> {
    const id = uuidv4();
    await db(this.TABLE_COMPLIANCE_CHECK).insert({
      id,
      ...checkData,
      checked_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getComplianceCheckById(id))!;
  }

  static async getComplianceCheckById(id: string): Promise<ComplianceCheck | null> {
    return await db(this.TABLE_COMPLIANCE_CHECK).where({ id }).first();
  }

  static async getComplianceCheckByProduct(productId: string): Promise<ComplianceCheck | null> {
    return await db(this.TABLE_COMPLIANCE_CHECK)
      .where({ productId })
      .orderBy('checked_at', 'desc')
      .first();
  }

  static async checkProductCompliance(tenantId: string, shopId: string, productId: string, platform: string): Promise<ComplianceCheck> {
    // 这里可以实现商品合规检查逻辑
    // 例如：检查商品是否符合平台政策、是否有侵权风险等
    const issues: string[] = [];
    
    // 模拟检查逻辑
    const rules = await this.getComplianceRules(platform);
    for (const rule of rules) {
      // 这里可以实现具体的规则检查
      if (Math.random() > 0.8) { // 模拟20%的概率触发违规
        issues.push(`违反规则: ${rule.ruleName}`);
      }
    }

    const status = issues.length === 0 ? 'COMPLIANT' : 'NON_COMPLIANT';

    return await this.createComplianceCheck({
      tenantId,
      shopId,
      productId,
      platform,
      status,
      issues
    });
  }

  // ==================== 合规规则管理 ====================

  static async createComplianceRule(ruleData: Partial<ComplianceRule>): Promise<ComplianceRule> {
    const id = uuidv4();
    await db(this.TABLE_COMPLIANCE_RULE).insert({
      id,
      ...ruleData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getComplianceRuleById(id))!;
  }

  static async getComplianceRuleById(id: string): Promise<ComplianceRule | null> {
    return await db(this.TABLE_COMPLIANCE_RULE).where({ id }).first();
  }

  static async getComplianceRules(platform: string): Promise<ComplianceRule[]> {
    return await db(this.TABLE_COMPLIANCE_RULE)
      .where({ platform })
      .where({ status: 'ACTIVE' })
      .orderBy('created_at', 'desc');
  }

  static async updateComplianceRule(id: string, ruleData: Partial<ComplianceRule>): Promise<ComplianceRule | null> {
    await db(this.TABLE_COMPLIANCE_RULE).where({ id }).update({
      ...ruleData,
      updated_at: new Date()
    });
    return await this.getComplianceRuleById(id);
  }

  // ==================== 政策监控 ====================

  static async createPolicyMonitor(monitorData: Partial<PolicyMonitor>): Promise<PolicyMonitor> {
    const id = uuidv4();
    await db(this.TABLE_POLICY_MONITOR).insert({
      id,
      ...monitorData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getPolicyMonitorById(id))!;
  }

  static async getPolicyMonitorById(id: string): Promise<PolicyMonitor | null> {
    return await db(this.TABLE_POLICY_MONITOR).where({ id }).first();
  }

  static async listPolicyMonitors(tenantId: string, platform: string): Promise<PolicyMonitor[]> {
    return await db(this.TABLE_POLICY_MONITOR)
      .where({ tenantId, platform })
      .orderBy('created_at', 'desc');
  }

  static async processPolicyChange(id: string, status: 'PROCESSED' | 'IGNORED'): Promise<PolicyMonitor | null> {
    await db(this.TABLE_POLICY_MONITOR).where({ id }).update({
      status,
      updated_at: new Date()
    });
    return await this.getPolicyMonitorById(id);
  }

  // ==================== 合规风险 ====================

  static async createComplianceRisk(riskData: Partial<ComplianceRisk>): Promise<ComplianceRisk> {
    const id = uuidv4();
    await db(this.TABLE_COMPLIANCE_RISK).insert({
      id,
      ...riskData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getComplianceRiskById(id))!;
  }

  static async getComplianceRiskById(id: string): Promise<ComplianceRisk | null> {
    return await db(this.TABLE_COMPLIANCE_RISK).where({ id }).first();
  }

  static async listComplianceRisks(tenantId: string, shopId: string, severity?: 'LOW' | 'MEDIUM' | 'HIGH'): Promise<ComplianceRisk[]> {
    let query = db(this.TABLE_COMPLIANCE_RISK).where({ tenantId, shopId });
    if (severity) {
      query = query.where({ severity });
    }
    return await query.orderBy('created_at', 'desc');
  }

  static async mitigateComplianceRisk(id: string, mitigationPlan: string): Promise<ComplianceRisk | null> {
    await db(this.TABLE_COMPLIANCE_RISK).where({ id }).update({
      status: 'MITIGATED',
      mitigationPlan,
      updated_at: new Date()
    });
    return await this.getComplianceRiskById(id);
  }

  static async resolveComplianceRisk(id: string): Promise<ComplianceRisk | null> {
    await db(this.TABLE_COMPLIANCE_RISK).where({ id }).update({
      status: 'RESOLVED',
      updated_at: new Date()
    });
    return await this.getComplianceRiskById(id);
  }

  // ==================== 数据合规 ====================

  static async createDataCompliance(complianceData: Partial<DataCompliance>): Promise<DataCompliance> {
    const id = uuidv4();
    await db(this.TABLE_DATA_COMPLIANCE).insert({
      id,
      ...complianceData,
      last_checked: new Date(),
      updated_at: new Date()
    });
    return (await this.getDataComplianceById(id))!;
  }

  static async getDataComplianceById(id: string): Promise<DataCompliance | null> {
    return await db(this.TABLE_DATA_COMPLIANCE).where({ id }).first();
  }

  static async getDataComplianceByType(tenantId: string, dataType: string): Promise<DataCompliance | null> {
    return await db(this.TABLE_DATA_COMPLIANCE)
      .where({ tenantId, dataType })
      .first();
  }

  static async checkDataCompliance(tenantId: string, dataType: string): Promise<DataCompliance> {
    // 这里可以实现数据合规检查逻辑
    // 例如：检查数据是否符合 GDPR、CCPA 等法规
    const status = Math.random() > 0.1 ? 'COMPLIANT' : 'NON_COMPLIANT'; // 模拟90%的概率合规

    return await this.createDataCompliance({
      tenantId,
      dataType,
      complianceStatus: status
    });
  }

  // ==================== 合规网关 ====================

  static async checkComplianceGate(tenantId: string, shopId: string, action: string, data: any): Promise<{
    allowed: boolean;
    reason?: string;
    riskLevel?: 'LOW' | 'MEDIUM' | 'HIGH';
  }> {
    // 这里可以实现合规网关逻辑
    // 例如：检查操作是否符合合规要求
    let allowed = true;
    let reason = '';
    let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' = 'LOW';

    switch (action) {
      case 'LIST_PRODUCT':
        // 检查商品是否合规
        if (data.productId) {
          const check = await this.getComplianceCheckByProduct(data.productId);
          if (check && check.status === 'NON_COMPLIANT') {
            allowed = false;
            reason = '商品不合规';
            riskLevel = 'HIGH';
          }
        }
        break;
      case 'CREATE_AD':
        // 检查广告是否合规
        if (data.adContent && data.adContent.includes('违规词')) {
          allowed = false;
          reason = '广告内容不合规';
          riskLevel = 'MEDIUM';
        }
        break;
      default:
        break;
    }

    return { allowed, reason, riskLevel };
  }

  // ==================== 合规审计 ====================

  static async logComplianceAction(tenantId: string, shopId: string, action: string, details: any): Promise<void> {
    await AuditService.log({
      tenantId,
      shopId,
      traceId: `compliance-${Date.now()}`,
      userId: 'system',
      module: 'COMPLIANCE',
      action: `COMPLIANCE_${action}`,
      resourceType: 'COMPLIANCE',
      afterSnapshot: details,
      result: 'success',
      source: 'node',
      businessType: 'TOC', // 默认为TOC，可根据实际情况调整
    });
  }

  static async getComplianceAuditLogs(tenantId: string, shopId: string, startDate: Date, endDate: Date): Promise<any[]> {
    // 直接从数据库查询审计日志
    return await db('cf_operation_log')
      .where({ tenant_id: tenantId })
      .where('action', 'like', 'COMPLIANCE_%')
      .where('created_at', '>=', startDate)
      .where('created_at', '<=', endDate)
      .orderBy('created_at', 'desc');
  }

  // ==================== 税务合规 ====================

  static async createTaxCompliance(taxData: Partial<TaxCompliance>): Promise<TaxCompliance> {
    const id = uuidv4();
    await db(this.TABLE_TAX_COMPLIANCE).insert({
      id,
      ...taxData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getTaxComplianceById(id))!;
  }

  static async getTaxComplianceById(id: string): Promise<TaxCompliance | null> {
    return await db(this.TABLE_TAX_COMPLIANCE).where({ id }).first();
  }

  static async listTaxCompliance(tenantId: string, shopId: string): Promise<TaxCompliance[]> {
    return await db(this.TABLE_TAX_COMPLIANCE)
      .where({ tenantId, shopId })
      .orderBy('due_date', 'asc');
  }

  static async updateTaxCompliance(id: string, taxData: Partial<TaxCompliance>): Promise<TaxCompliance | null> {
    await db(this.TABLE_TAX_COMPLIANCE).where({ id }).update({
      ...taxData,
      updated_at: new Date()
    });
    return await this.getTaxComplianceById(id);
  }

  static async checkTaxCompliance(tenantId: string, shopId: string, taxType: string): Promise<TaxCompliance> {
    // 这里可以实现税务合规检查逻辑
    const status = Math.random() > 0.1 ? 'COMPLIANT' : 'NON_COMPLIANT'; // 模拟90%的概率合规

    return await this.createTaxCompliance({
      tenantId,
      shopId,
      taxType,
      status,
      filingDate: new Date(),
      dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天后到期
      amount: 0,
      currency: 'USD'
    });
  }

  // ==================== 安全合规 ====================

  static async configureSecurity(config: SecurityConfig): Promise<{ success: boolean; message: string }> {
    try {
      this.securityConfigs.set(config.id, config);
      this.securityStatus.set(config.id, {
        status: 'ACTIVE',
        lastUpdated: new Date(),
        complianceLevel: 'COMPLIANT'
      });

      logger.info(`Security config ${config.id} configured successfully`);
      return { success: true, message: 'Security config configured successfully' };
    } catch (error) {
      logger.error(`Error configuring security: ${error}`);
      return { success: false, message: `Error configuring security: ${error}` };
    }
  }

  static async runComplianceCheck(checkId: string, target: string): Promise<ComplianceResult> {
    try {
      const check = this.complianceChecks.get(checkId);
      if (!check) {
        return {
          checkId,
          target,
          status: 'ERROR',
          message: 'Compliance check not found',
          timestamp: new Date(),
          details: {}
        };
      }

      // 模拟合规检查
      await new Promise(resolve => setTimeout(resolve, 1500));

      // 随机生成合规结果
      const isCompliant = Math.random() > 0.2; // 80% 概率合规

      const result: ComplianceResult = {
        checkId,
        target,
        status: isCompliant ? 'PASSED' : 'FAILED',
        message: isCompliant ? 'Compliance check passed' : 'Compliance check failed',
        timestamp: new Date(),
        details: {
          checkType: check.type,
          remediation: isCompliant ? null : `Please fix ${check.type} issues in ${target}`
        }
      };

      logger.info(`Compliance check ${checkId} completed for ${target}, result: ${result.status}`);
      return result;
    } catch (error) {
      logger.error(`Error running compliance check: ${error}`);
      return {
        checkId,
        target,
        status: 'ERROR',
        message: `Error running compliance check: ${error}`,
        timestamp: new Date(),
        details: {}
      };
    }
  }

  static async registerComplianceCheck(check: SecurityComplianceCheck): Promise<{ success: boolean; message: string }> {
    try {
      this.complianceChecks.set(check.id, check);

      logger.info(`Compliance check ${check.id} registered successfully`);
      return { success: true, message: 'Compliance check registered successfully' };
    } catch (error) {
      logger.error(`Error registering compliance check: ${error}`);
      return { success: false, message: `Error registering compliance check: ${error}` };
    }
  }

  static async getSecurityStatus(configId: string): Promise<SecurityStatus | null> {
    try {
      const status = this.securityStatus.get(configId);
      if (!status) {
        return null;
      }

      return status;
    } catch (error) {
      logger.error(`Error getting security status: ${error}`);
      return null;
    }
  }

  static async listSecurityConfigs(): Promise<Array<{ id: string; config: SecurityConfig; status: SecurityStatus }>> {
    try {
      const configs: Array<{ id: string; config: SecurityConfig; status: SecurityStatus }> = [];

      for (const [id, config] of this.securityConfigs.entries()) {
        const status = this.securityStatus.get(id) || {
          status: 'INACTIVE' as const,
          lastUpdated: new Date(),
          complianceLevel: 'PENDING' as const
        };
        configs.push({ id, config, status });
      }

      return configs;
    } catch (error) {
      logger.error(`Error listing security configs: ${error}`);
      return [];
    }
  }

  static async listComplianceChecks(): Promise<SecurityComplianceCheck[]> {
    try {
      return Array.from(this.complianceChecks.values());
    } catch (error) {
      logger.error(`Error listing compliance checks: ${error}`);
      return [];
    }
  }

  static async runAllComplianceChecks(target: string): Promise<ComplianceResult[]> {
    try {
      const results: ComplianceResult[] = [];

      for (const check of this.complianceChecks.values()) {
        const result = await this.runComplianceCheck(check.id, target);
        results.push(result);
      }

      return results;
    } catch (error) {
      logger.error(`Error running all compliance checks: ${error}`);
      return [];
    }
  }

  static async updateSecurityConfig(configId: string, updates: Partial<SecurityConfig>): Promise<{ success: boolean; message: string }> {
    try {
      const config = this.securityConfigs.get(configId);
      if (!config) {
        return { success: false, message: 'Security config not found' };
      }

      // 更新配置
      const updatedConfig = { ...config, ...updates };
      this.securityConfigs.set(configId, updatedConfig);

      // 更新状态
      const status = this.securityStatus.get(configId);
      if (status) {
        status.lastUpdated = new Date();
        this.securityStatus.set(configId, status);
      }

      logger.info(`Security config ${configId} updated successfully`);
      return { success: true, message: 'Security config updated successfully' };
    } catch (error) {
      logger.error(`Error updating security config: ${error}`);
      return { success: false, message: `Error updating security config: ${error}` };
    }
  }

  static async deleteSecurityConfig(configId: string): Promise<{ success: boolean; message: string }> {
    try {
      const config = this.securityConfigs.get(configId);
      if (!config) {
        return { success: false, message: 'Security config not found' };
      }

      this.securityConfigs.delete(configId);
      this.securityStatus.delete(configId);

      logger.info(`Security config ${configId} deleted successfully`);
      return { success: true, message: 'Security config deleted successfully' };
    } catch (error) {
      logger.error(`Error deleting security config: ${error}`);
      return { success: false, message: `Error deleting security config: ${error}` };
    }
  }

  static async deleteComplianceCheck(checkId: string): Promise<{ success: boolean; message: string }> {
    try {
      const check = this.complianceChecks.get(checkId);
      if (!check) {
        return { success: false, message: 'Compliance check not found' };
      }

      this.complianceChecks.delete(checkId);

      logger.info(`Compliance check ${checkId} deleted successfully`);
      return { success: true, message: 'Compliance check deleted successfully' };
    } catch (error) {
      logger.error(`Error deleting compliance check: ${error}`);
      return { success: false, message: `Error deleting compliance check: ${error}` };
    }
  }

  static async generateSecurityReport(): Promise<{ success: boolean; report: any; message: string }> {
    try {
      const configs = await this.listSecurityConfigs();
      const checks = await this.listComplianceChecks();

      const report = {
        generatedAt: new Date(),
        summary: {
          totalConfigs: configs.length,
          totalChecks: checks.length,
          compliantConfigs: configs.filter(c => c.status.complianceLevel === 'COMPLIANT').length
        },
        details: {
          configs,
          checks
        }
      };

      logger.info('Security report generated successfully');
      return { success: true, report, message: 'Security report generated successfully' };
    } catch (error) {
      logger.error(`Error generating security report: ${error}`);
      return { success: false, report: null, message: `Error generating security report: ${error}` };
    }
  }

  // ==================== 库存同步合规 ====================

  static async atomicSync(req: { tenantId: string; productId: string; platform: string; newStock: number; traceId: string }): Promise<boolean> {
    logger.info(`[ComplianceService] Syncing Product ${req.productId} to ${req.platform} (Stock: ${req.newStock})`);

    const startTime = Date.now();

    try {
      // 1. 获取旧库存记录 (用于审计)
      const oldStock = await db('cf_inventory')
        .where({ tenant_id: req.tenantId, product_id: req.productId })
        .first();

      // 2. 模拟调用外部平台 API 更新库存
      // 在实际业务中，此处会调用 ShopifyConnector / TikTokConnector 等
      const apiSuccess = await this.mockPlatformApiCall(req.platform, req.productId, req.newStock);

      if (!apiSuccess) throw new Error('Platform API call failed');

      // 3. 记录同步日志
      await db(this.TABLE_INVENTORY_SYNC_LOGS).insert({
        tenant_id: req.tenantId,
        product_id: req.productId,
        platform: req.platform,
        old_stock: oldStock?.available_stock || 0,
        new_stock: req.newStock,
        status: 'SUCCESS',
        trace_id: req.traceId,
        created_at: new Date(),
        updated_at: new Date()
      });

      const duration = Date.now() - startTime;
      logger.info(`[ComplianceService] Sync completed in ${duration}ms for ${req.platform}`);

      return true;
    } catch (err: any) {
      logger.error(`[ComplianceService] Sync failed for ${req.platform}: ${err.message}`);
      
      await db(this.TABLE_INVENTORY_SYNC_LOGS).insert({
        tenant_id: req.tenantId,
        product_id: req.productId,
        platform: req.platform,
        status: 'FAILED',
        trace_id: req.traceId,
        created_at: new Date(),
        updated_at: new Date()
      });

      return false;
    }
  }

  private static async mockPlatformApiCall(platform: string, productId: string, stock: number): Promise<boolean> {
    // 模拟 10-50ms 的 API 延迟
    await new Promise(resolve => setTimeout(resolve, 10 + Math.random() * 40));
    return true;
  }

  static async getSyncHealth(tenantId: string): Promise<any> {
    const total = await db(this.TABLE_INVENTORY_SYNC_LOGS).where({ tenant_id: tenantId }).count('id as count').first();
    const failed = await db(this.TABLE_INVENTORY_SYNC_LOGS).where({ tenant_id: tenantId, status: 'FAILED' }).count('id as count').first();

    return {
      tenantId,
      successRate: total?.count ? (1 - Number(failed?.count || 0) / Number(total.count)) : 1,
      lastSyncAt: new Date().toISOString()
    };
  }

  // ==================== 初始化方法 ====================

  static async initTable() {
    logger.info('🚀 ComplianceService tables initialized');
    // 这里可以添加数据库表初始化逻辑
  }
}

