import { logger } from '../utils/logger';

export interface TaxConfig {
  countryCode: string;
  vatRate: number;
  dutyRate: number;
  iossThreshold?: number; // IOSS 阈值 (如 150 EUR)
}

export interface TaxCalculationRequest {
  countryCode: string;
  baseAmount: number;
  currency: string;
  isB2B?: boolean;
  iossNumber?: string;
}

/**
 * TaxService: 全球税务合规引擎核心逻辑 (BIZ_EXT_08)
 * 负责税率自动匹配与 IOSS 报关数据准备
 */
export class TaxService {
  private static taxRates: Record<string, TaxConfig> = {
    'UK': { countryCode: 'UK', vatRate: 0.20, dutyRate: 0.02, iossThreshold: 135 }, // 135 GBP
    'DE': { countryCode: 'DE', vatRate: 0.19, dutyRate: 0.00, iossThreshold: 150 }, // 150 EUR
    'FR': { countryCode: 'FR', vatRate: 0.20, dutyRate: 0.00, iossThreshold: 150 },
    'US': { countryCode: 'US', vatRate: 0.00, dutyRate: 0.05 } // 州税由平台代缴或另计
  };

  /**
   * [BIZ_FIN_02] 实时税务计提逻辑
   * 根据目的国、金额与 IOSS 规则自动匹配税率
   */
  static calculateTax(request: TaxCalculationRequest | number, countryCode?: string) {
    let amount: number;
    let code: string;
    let currency: string = 'USD';

    if (typeof request === 'object') {
      amount = request.baseAmount;
      code = request.countryCode;
      currency = request.currency;
    } else {
      amount = request;
      code = countryCode || 'US';
    }

    const config = this.taxRates[code] || { countryCode: code, vatRate: 0.10, dutyRate: 0 }; // 默认 10% 兜底
    
    // IOSS 规则逻辑 (BIZ_FIN_02)
    let vatAmount = amount * config.vatRate;
    let dutyAmount = amount * config.dutyRate;
    let isIOSS = false;

    if (config.iossThreshold && amount <= config.iossThreshold) {
      isIOSS = true;
      // IOSS 模式下，VAT 由平台代扣代缴，但卖家仍需计提以准确核算利润
      logger.info(`[TaxEngine] IOSS applicable for ${code}, Amount: ${amount} ${currency}`);
    } else if (config.iossThreshold && amount > config.iossThreshold) {
      // 超过阈值，可能涉及 DDU/DDP 模式，税费由买家或卖家承担
      dutyAmount += amount * 0.05; // 额外关税预估
      logger.warn(`[TaxEngine] Threshold exceeded for ${code}, triggering additional duty estimation`);
    }

    const totalTax = vatAmount + dutyAmount;
    const totalWithTax = amount + totalTax;

    return {
      originalAmount: amount,
      vatAmount,
      dutyAmount,
      totalTax,
      total: totalWithTax,
      isIOSS,
      config
    };
  }

  /**
   * 生成 IOSS 报关电子报文 (Mock)
   */
  static generateIOSSDeclaration(orderId: string) {
    logger.info(`[TaxEngine] Generating IOSS declaration for order: ${orderId}`);
    return {
      declarationId: `IOSS-${orderId}-${Date.now()}`,
      status: 'READY_TO_SUBMIT',
      platformIOSS: 'IM1234567890'
    };
  }
}
