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

/**
 * [BIZ_FIN_188] 多国税务合规申报文件自动预填建议 (Filing)
 * @description 联动销售明细，预填各国税务申报建议。
 */
export class TaxFilingAdvisor {
  private static readonly FILING_TABLE = 'cf_tax_filing_advisories';

  /**
   * 生成税务申报建议
   */
  static async generateTaxFilingAdvisory(tenantId: string, country: string) {
    logger.info(`[TaxFiling] Generating advisory for country: ${country} for tenant: ${tenantId}`);

    // 1. 获取该国家过去一季度的销售额
    const quarterStart = new Date();
    quarterStart.setMonth(quarterStart.getMonth() - 3);

    const stats = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, destination_country: country })
      .andWhere('created_at', '>=', quarterStart)
      .select(
        db.raw('SUM(total_amount) as totalSales'),
        db.raw('SUM(tax_amount) as totalTaxCollected')
      );

    const totalSales = Number(stats[0].totalSales || 0);
    const totalTaxCollected = Number(stats[0].totalTaxCollected || 0);

    // 2. 生成建议
    const advisory = {
      id: `TF-${tenantId}-${country}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      country,
      period: 'CURRENT_QUARTER',
      totalSales,
      totalTaxCollected,
      filingDeadline: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000), // 假设 15 天后截止
      status: 'READY_TO_FILE',
      created_at: new Date()
    };

    // 3. 存储建议
    await db(this.FILING_TABLE)
      .insert(advisory)
      .onConflict(['id'])
      .merge();

    return advisory;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.FILING_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.FILING_TABLE} table...`);
      await db.schema.createTable(this.FILING_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('country', 64).notNullable();
        table.string('period', 64);
        table.decimal('totalSales', 15, 2);
        table.decimal('totalTaxCollected', 15, 2);
        table.timestamp('filingDeadline');
        table.string('status', 20);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'country']);
      });
    }
  }
}
