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

export interface InvoiceItem {
  skuId: string;
  description: string;
  quantity: number;
  unitPrice: number;
  taxRate: number;
  taxAmount: number;
  total: number;
}

export interface Invoice {
  invoiceNumber: string;
  tenantId: string;
  orderId: string;
  customerName: string;
  customerEmail: string;
  billingAddress: string;
  countryCode: string;
  currency: string;
  items: InvoiceItem[];
  subtotal: number;
  totalTax: number;
  grandTotal: number;
  createdAt: Date;
  status: 'ISSUED' | 'VOID' | 'PAID';
}

/**
 * [BIZ_FIN_05] 全球发票自动化生成与合规引擎 (Auto-Invoicing)
 * @description 核心逻辑：根据订单与目的地国家法律要求自动生成合规发票（支持 VAT/GST）。
 */
export class InvoicingService {
  private static readonly INVOICE_TABLE = 'cf_invoices';

  /**
   * 为订单生成发票
   */
  static async generateInvoice(orderId: string, tenantId: string): Promise<Invoice> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_FIN_INVOICING', tenantId))) {
      logger.info(`[Invoicing] Service is disabled for Tenant ${tenantId}`);
      throw new Error('Feature BIZ_FIN_INVOICING is disabled');
    }

    logger.info(`[Invoicing] Generating invoice for Order ${orderId}`);

    // 1. 获取订单与商品详情 (Mock)
    const order = await db('cf_orders').where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error('Order not found for invoicing.');

    // 2. 根据目的地国家确定税率 (VAT/GST Logic)
    const taxRate = this.getTaxRateForCountry(order.countryCode);

    // 3. 构建发票明细
    const items: InvoiceItem[] = [
      {
        skuId: 'SKU-001', // 简化处理
        description: order.productTitle || 'Product Name',
        quantity: 1,
        unitPrice: order.price,
        taxRate: taxRate,
        taxAmount: order.price * taxRate,
        total: order.price * (1 + taxRate)
      }
    ];

    const subtotal = items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0);
    const totalTax = items.reduce((sum, item) => sum + item.taxAmount, 0);
    const grandTotal = subtotal + totalTax;

    const invoice: Invoice = {
      invoiceNumber: `INV-${Date.now()}`,
      tenantId,
      orderId,
      customerName: order.customerName || 'Walk-in Customer',
      customerEmail: order.customerEmail || 'no-email@provided.com',
      billingAddress: order.address || 'N/A',
      countryCode: order.countryCode,
      currency: order.currency || 'USD',
      items,
      subtotal: Number(subtotal.toFixed(2)),
      totalTax: Number(totalTax.toFixed(2)),
      grandTotal: Number(grandTotal.toFixed(2)),
      createdAt: new Date(),
      status: 'ISSUED'
    };

    // 4. 保存到数据库
    await db(this.INVOICE_TABLE).insert({
      id: invoice.invoiceNumber,
      tenant_id: invoice.tenantId,
      order_id: invoice.orderId,
      grand_total: invoice.grandTotal,
      tax_amount: invoice.totalTax,
      country_code: invoice.countryCode,
      status: invoice.status,
      items_json: JSON.stringify(invoice.items),
      created_at: invoice.createdAt,
      updated_at: new Date()
    });

    return invoice;
  }

  /**
   * 模拟各国的增值税/消费税逻辑
   */
  private static getTaxRateForCountry(countryCode: string): number {
    const rates: Record<string, number> = {
      'GB': 0.20, // UK VAT
      'DE': 0.19, // Germany VAT
      'FR': 0.20, // France VAT
      'AU': 0.10, // Australia GST
      'US': 0.00, // US (Simplified, Sales tax is state-level)
      'CN': 0.13  // China VAT
    };
    return rates[countryCode] || 0.00;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.INVOICE_TABLE);
    if (!exists) {
      logger.info(`📦 Creating ${this.INVOICE_TABLE} table...`);
      await db.schema.createTable(this.INVOICE_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('order_id', 64).notNullable();
        table.decimal('grand_total', 15, 2);
        table.decimal('tax_amount', 15, 2);
        table.string('country_code', 10);
        table.string('status', 20);
        table.json('items_json');
        table.timestamps(true, true);

        table.index(['tenant_id', 'order_id']);
      });
    }
  }
}
