import db from '../../config/database';
import { logger } from '../../utils/logger';

export interface TaxRouteOption {
  method: 'IOSS' | 'OSS' | 'DDP' | 'DDU';
  estimatedTax: number;
  complianceFee: number;
  totalCost: number;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
}

/**
 * [BIZ_FIN_60] 跨主权税务路由优化引擎 (Tax Routing Optimizer)
 * @description 在多个目的国发货时，自动选择税务成本最低（如 IOSS vs OSS）的路由。
 */
export class TaxRoutingOptimizerService {
  private static readonly ROUTE_LOG_TABLE = 'cf_tax_routing_logs';

  /**
   * 优化税务路由
   */
  static async optimizeTaxRoute(params: {
    tenantId: string;
    destinationCountry: string;
    orderValue: number;
    currency: string;
  }) {
    logger.info(`[TaxRouting] Optimizing tax route for ${params.destinationCountry} (Value: ${params.orderValue})`);

    const options: TaxRouteOption[] = [];

    // 1. 模拟 IOSS 选项 (针对欧盟 < 150 EUR)
    if (['DE', 'FR', 'IT', 'ES'].includes(params.destinationCountry) && params.orderValue < 150) {
      options.push({
        method: 'IOSS',
        estimatedTax: params.orderValue * 0.20,
        complianceFee: 1.5,
        totalCost: (params.orderValue * 0.20) + 1.5,
        riskLevel: 'LOW'
      });
    }

    // 2. 模拟 DDP 选项 (商家代缴)
    options.push({
      method: 'DDP',
      estimatedTax: params.orderValue * 0.22,
      complianceFee: 5.0,
      totalCost: (params.orderValue * 0.22) + 5.0,
      riskLevel: 'LOW'
    });

    // 3. 模拟 DDU 选项 (买家自缴 - 风险高)
    options.push({
      method: 'DDU',
      estimatedTax: 0,
      complianceFee: 0,
      totalCost: 0,
      riskLevel: 'HIGH'
    });

    // 4. 选择最优路由 (Total Cost 最小且风险非 HIGH)
    const sorted = options.filter(o => o.riskLevel !== 'HIGH').sort((a, b) => a.totalCost - b.totalCost);
    const optimal = sorted.length > 0 ? sorted[0] : options.find(o => o.method === 'DDU');

    // 5. 记录决策
    if (optimal) {
      await db(this.ROUTE_LOG_TABLE).insert({
        tenant_id: params.tenantId,
        destination_country: params.destinationCountry,
        order_value: params.orderValue,
        chosen_method: optimal.method,
        estimated_tax: optimal.estimatedTax,
        total_cost: optimal.totalCost,
        created_at: new Date()
      });
    }

    return optimal;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.ROUTE_LOG_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.ROUTE_LOG_TABLE} table...`);
      await db.schema.createTable(this.ROUTE_LOG_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('destination_country', 10).notNullable();
        table.decimal('order_value', 15, 2);
        table.string('chosen_method', 20);
        table.decimal('estimated_tax', 15, 2);
        table.decimal('total_cost', 15, 2);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'destination_country']);
      });
    }
  }
}
