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

/**
 * [BIZ_FIN_26] 主权微贷与流动性注入 (MicroCreditService)
 * @description 在自治生态中，根据租户在主权账本中的历史贡献、声誉分及 AGI 预测的未来 GMV，自动为中小租户提供亚秒级的微额授信与流动性注入。
 */
export class MicroCreditService {
  private static readonly MICRO_CREDIT_TABLE = 'cf_sov_micro_credit';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.MICRO_CREDIT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.MICRO_CREDIT_TABLE} table...`);
      await db.schema.createTable(this.MICRO_CREDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.decimal('credit_limit', 20, 2).notNullable(); // 授信额度
        table.decimal('utilized_amount', 20, 2).defaultTo(0); // 已使用额度
        table.float('interest_rate').defaultTo(0.05); // AGI 动态计算的利率
        table.string('credit_status', 32).defaultTo('ACTIVE'); // ACTIVE, FROZEN, REPAID
        table.json('credit_scoring_logic'); // AGI 评分依据
        table.string('trace_id', 128);
        table.timestamps(true, true);
        table.index(['tenant_id', 'credit_status']);
      });
      logger.info(`✅ Table ${this.MICRO_CREDIT_TABLE} created`);
    }
  }

  /**
   * 自动授信评估与注入
   */
  static async evaluateAndInjectCredit(tenantId: string, traceId: string): Promise<number> {
    if (!(await FeatureGovernanceService.isEnabled('BIZ_FIN_MICRO_CREDIT', tenantId))) {
      return 0;
    }

    logger.info(`[MicroCredit] Evaluating credit for tenant ${tenantId} | traceId: ${traceId}`);

    // 1. AGI 进行信用评分
    const scoringPrompt = `Score credit for tenant ${tenantId} based on ecosystem contributions, reputation, and historical fulfillment.`;
    const scoreResult = await AIService.generateStrategy(scoringPrompt, traceId);

    // 2. 解析评分并计算额度 (模拟)
    const creditLimit = scoreResult.includes('PREMIUM') ? 100000.00 : 25000.00;
    const rate = scoreResult.includes('LOW_RISK') ? 0.03 : 0.08;

    // 3. 注入/更新额度
    await db(this.MICRO_CREDIT_TABLE)
      .insert({
        tenant_id: tenantId,
        credit_limit: creditLimit,
        interest_rate: rate,
        credit_status: 'ACTIVE',
        credit_scoring_logic: JSON.stringify({ score: scoreResult }),
        trace_id: traceId,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict('tenant_id')
      .merge();

    logger.info(`[MicroCredit] Injected ${creditLimit} credit for tenant ${tenantId} @ ${rate * 100}% | traceId: ${traceId}`);
    return creditLimit;
  }

  /**
   * 预占授信额度
   */
  static async reserveCredit(tenantId: string, amount: number): Promise<boolean> {
    const credit = await db(this.MICRO_CREDIT_TABLE).where({ tenant_id: tenantId, credit_status: 'ACTIVE' }).first();
    if (!credit) return false;

    const available = parseFloat(credit.credit_limit) - parseFloat(credit.utilized_amount);
    if (available < amount) return false;

    await db(this.MICRO_CREDIT_TABLE)
      .where({ id: credit.id })
      .update({
        utilized_amount: parseFloat(credit.utilized_amount) + amount,
        updated_at: new Date()
      });
    
    return true;
  }
}
