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

export interface InvoiceData {
  orderId: string;
  tenantId: string;
  type: 'VAT' | 'GST' | 'STANDARD';
  totalAmount: number;
  currency: string;
  taxBreakdown: any;
}

/**
 * [BIZ_FIN_05] 全球发票自动化生成服务
 * @description 支持 VAT/GST 模板，自动根据订单国家生成合规发票
 */
export class InvoicingService {
  private static readonly TABLE_NAME = 'cf_invoices';

  /**
   * 为订单生成发票 (BIZ_FIN_05)
   */
  static async generateInvoice(data: InvoiceData): Promise<string> {
    logger.info(`[Invoice] Generating ${data.type} invoice for Order: ${data.orderId}`);

    const invoiceNumber = `INV-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    
    // 1. 模拟 PDF 生成逻辑 (实际中应集成 PDF 库)
    const pdfUrl = `https://storage.crawlful.com/invoices/${invoiceNumber}.pdf`;

    // 2. 持久化记录
    await db(this.TABLE_NAME).insert({
      tenant_id: data.tenantId,
      order_id: data.orderId,
      invoice_number: invoiceNumber,
      type: data.type,
      total_amount: data.totalAmount,
      currency: data.currency,
      tax_breakdown: JSON.stringify(data.taxBreakdown),
      pdf_url: pdfUrl,
      status: 'GENERATED',
      created_at: new Date(),
      updated_at: new Date()
    });

    return invoiceNumber;
  }

  /**
   * 根据目的地国家确定发票类型 (BIZ_FIN_05)
   */
  static determineInvoiceType(countryCode: string): 'VAT' | 'GST' | 'STANDARD' {
    const vatCountries = ['DE', 'FR', 'IT', 'ES', 'PL', 'NL', 'BE'];
    const gstCountries = ['AU', 'NZ', 'SG', 'IN'];

    if (vatCountries.includes(countryCode)) return 'VAT';
    if (gstCountries.includes(countryCode)) return 'GST';
    return 'STANDARD';
  }
}
