import db from '../../config/database';
import { AuditService } from '../../services/AuditService';
import { PricingParams, PricingService, ProfitSnapshot } from '../../services/PricingService';
import { logger } from '../../utils/logger';

export interface ArbitrageOpportunity {
  id: string;
  sourceUrl: string;
  targetPlatform: string;
  profitSnapshot: ProfitSnapshot;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'BLOCK';
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'EXECUTED';
}

/**
 * [BIZ_ARB_01] 套利识别与测算服务
 * @description 核心业务策略逻辑：跨平台利差发现与实时风控
 */
export class ArbitrageService {
  private static readonly TABLE_NAME = 'cf_arbitrage_records';

  /**
   * 测算套利机会
   */
  static async analyzeOpportunity(params: PricingParams, sourceUrl: string): Promise<ArbitrageOpportunity> {
    const profitSnapshot = await PricingService.calculateNetProfit(params);
    
    // 风控策略：利润率低于 15% 或 ROI 低于 20% 标记为高风险
    let riskLevel: ArbitrageOpportunity['riskLevel'] = 'LOW';
    if (profitSnapshot.profitRate < 0.15 || profitSnapshot.roi < 0.2) {
      riskLevel = 'HIGH';
    } else if (profitSnapshot.profitRate < 0.25) {
      riskLevel = 'MEDIUM';
    }

    // 拦截极其低利润的套利
    if (profitSnapshot.profitRate < 0.05) {
      riskLevel = 'BLOCK';
      // 记录审计日志
      await AuditService.log({
        tenantId: 'SYSTEM', // 或从上下文获取
        traceId: `risk-${Date.now()}`,
        userId: 'system',
        module: 'FINANCE',
        action: 'ARB_RISK_BLOCK',
        resourceType: 'arbitrage',
        resourceId: sourceUrl,
        metadata: { profitSnapshot },
        result: 'failed',
        source: 'node'
      });
    }

    const opportunity: ArbitrageOpportunity = {
      id: `ARB-${Date.now()}`,
      sourceUrl,
      targetPlatform: params.platform,
      profitSnapshot,
      riskLevel,
      status: 'PENDING'
    };

    return opportunity;
  }

  /**
   * 保存套利记录
   */
  static async recordOpportunity(tenantId: string, opportunity: ArbitrageOpportunity) {
    const [id] = await db(this.TABLE_NAME).insert({
      tenant_id: tenantId,
      source_url: opportunity.sourceUrl,
      target_platform: opportunity.targetPlatform,
      initial_profit_rate: opportunity.profitSnapshot.profitRate,
      initial_roi: opportunity.profitSnapshot.roi,
      profit_snapshot: JSON.stringify(opportunity.profitSnapshot),
      risk_level: opportunity.riskLevel,
      status: opportunity.status,
      created_at: new Date(),
      updated_at: new Date()
    });

    return id;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.TABLE_NAME);
    if (!exists) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('source_url', 512).notNullable();
        table.string('target_platform', 32).notNullable();
        table.float('initial_profit_rate');
        table.float('initial_roi');
        table.json('profit_snapshot');
        table.string('risk_level', 16);
        table.string('status', 32).defaultTo('PENDING');
        table.integer('sales_count').defaultTo(0);
        table.float('conversion_rate').defaultTo(0);
        table.timestamps(true, true);

        table.index(['tenant_id', 'status']);
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }
}
