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

/**
 * [BIZ_FIN_181] 多平台合规成本 (ERP/工具费) 摊销建议 (Amortization)
 * @description 按照 SKU 级摊销 ERP, 工具费等合规成本。
 */
export class ExpenseService {
  private static readonly AMORTIZATION_TABLE = 'cf_expense_amortizations';

  /**
   * 摊销合规成本
   */
  static async amortizeComplianceCosts(tenantId: string) {
    logger.info(`[Expense] Amortizing compliance costs for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的总合规成本 (ERP/工具费)
    const costs = await db('cf_expenses')
      .where({ tenant_id: tenantId, category: 'COMPLIANCE' })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(db.raw('SUM(amount) as totalComplianceCost'));

    const totalComplianceCost = Number(costs[0].totalComplianceCost || 0);

    // 2. 获取过去 30 天的总订单数
    const orders = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(db.raw('COUNT(id) as totalOrders'));

    const totalOrders = Number(orders[0].totalOrders || 0);

    if (totalOrders === 0) return null;

    const costPerOrder = totalComplianceCost / totalOrders;

    const amortizationRecord = {
      id: `AM-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      totalComplianceCost: Number(totalComplianceCost.toFixed(2)),
      totalOrders,
      costPerOrder: Number(costPerOrder.toFixed(4)),
      created_at: new Date()
    };

    // 3. 存储摊销记录
    await db(this.AMORTIZATION_TABLE)
      .insert(amortizationRecord)
      .onConflict(['id'])
      .merge();

    return amortizationRecord;
  }

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