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

/**
 * [BIZ_FIN_169] 租户资源超限自动计费单生成 (Billing)
 * @description 自动化资源超限计费逻辑。
 */
export class BillingEngine {
  private static readonly INVOICE_TABLE = 'cf_resource_invoices';

  /**
   * 生成资源超限计费单
   */
  static async generateResourceInvoice(tenantId: string) {
    logger.info(`[BillingEngine] Generating resource invoice for tenant: ${tenantId}`);

    // 1. 获取租户配额和实际用量
    const quota = await db('cf_tenant_quota').where({ tenant_id: tenantId }).first();
    if (!quota) return null;

    // 假设超限逻辑 (模拟)
    const usage = {
      aiCalls: 1200, // 假设实际用了 1200 次
      storageGb: 150 // 假设实际用了 150GB
    };

    const aiCallLimit = Number(quota.ai_call_limit || 1000);
    const storageLimit = Number(quota.storage_limit || 100);

    let overageAmount = 0;
    const overageDetails = [];

    if (usage.aiCalls > aiCallLimit) {
      const overAi = usage.aiCalls - aiCallLimit;
      const fee = overAi * 0.05; // $0.05 per extra call
      overageAmount += fee;
      overageDetails.push(`AI Calls overage: ${overAi} units ($${fee.toFixed(2)})`);
    }

    if (usage.storageGb > storageLimit) {
      const overStorage = usage.storageGb - storageLimit;
      const fee = overStorage * 0.2; // $0.2 per extra GB
      overageAmount += fee;
      overageDetails.push(`Storage overage: ${overStorage} GB ($${fee.toFixed(2)})`);
    }

    if (overageAmount === 0) return null;

    const invoice = {
      id: `RI-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      amount: Number(overageAmount.toFixed(2)),
      details: overageDetails.join('; '),
      status: 'PENDING',
      created_at: new Date()
    };

    // 2. 存储计费单
    await db(this.INVOICE_TABLE)
      .insert(invoice)
      .onConflict(['id'])
      .merge();

    return invoice;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.INVOICE_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.INVOICE_TABLE} table...`);
      await db.schema.createTable(this.INVOICE_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.decimal('amount', 15, 2);
        table.text('details');
        table.string('status', 20); // E.g., PENDING, PAID, VOID
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId']);
      });
    }
  }
}
