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

export interface TaxReport {
  tenantId: string;
  month: string; // YYYY-MM
  totalVat: number;
  totalGst: number;
  orderCount: number;
}

/**
 * [BIZ_FIN_07] 租户级税务合规月报自动生成服务
 * @description 汇总单月所有订单的税务计提记录，生成符合 IOSS/VAT 申报要求的月度报表
 */
export class TaxReportService {
  private static readonly REPORT_TABLE = 'cf_tax_reports';

  /**
   * 初始化表
   */
  static async initTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.REPORT_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.REPORT_TABLE} table...`);
      await db.schema.createTable(this.REPORT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('month', 16).notNullable();
        table.float('total_vat').defaultTo(0);
        table.float('total_gst').defaultTo(0);
        table.integer('order_count').defaultTo(0);
        table.string('pdf_url', 255);
        table.timestamps(true, true);
        table.unique(['tenant_id', 'month']);
      });
      console.log(`✅ Table ${this.REPORT_TABLE} created`);
    }
  }

  /**
   * 生成月度税务报告 (BIZ_FIN_07)
   */
  static async generateMonthlyReport(tenantId: string, month: string): Promise<TaxReport> {
    logger.info(`[TaxReport] Generating report for Tenant: ${tenantId}, Month: ${month}`);

    // 1. 汇总当月税务记录
    const startTime = new Date(`${month}-01T00:00:00Z`);
    const endTime = new Date(startTime);
    endTime.setMonth(endTime.getMonth() + 1);

    const stats = await db('cf_tax_accruals')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', startTime)
      .andWhere('created_at', '<', endTime)
      .select(
        db.raw('SUM(CASE WHEN type = "VAT" THEN amount ELSE 0 END) as totalVat'),
        db.raw('SUM(CASE WHEN type = "GST" THEN amount ELSE 0 END) as totalGst'),
        db.raw('COUNT(id) as orderCount')
      )
      .first();

    const report: TaxReport = {
      tenantId,
      month,
      totalVat: stats?.totalVat || 0,
      totalGst: stats?.totalGst || 0,
      orderCount: stats?.orderCount || 0
    };

    // 2. 持久化报告
    await db(this.REPORT_TABLE).insert({
      tenant_id: tenantId,
      month: month,
      total_vat: report.totalVat,
      total_gst: report.totalGst,
      order_count: report.orderCount,
      pdf_url: `https://storage.crawlful.com/reports/tax-${tenantId}-${month}.pdf`,
      created_at: new Date(),
      updated_at: new Date()
    }).onConflict(['tenant_id', 'month']).merge();

    return report;
  }
}
