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

export interface CreditScore {
  tenantId: string;
  score: number; // 0-1000
  tier: 'SILVER' | 'GOLD' | 'PLATINUM' | 'DIAMOND';
  availableCredit: number;
  lastAssessmentDate: Date;
}

/**
 * [BIZ_FIN_35] 基于 ZKP 的全球主权微贷资金池 (Credit Pool)
 * @description 核心逻辑：在保护租户经营隐私的前提下，利用 AGI 评估其信用等级，
 * 并建立主权级微贷池，支持跨租户资金周转。
 * 这里模拟 ZKP 信用证明逻辑：仅输出证明 (Proof) 与得分，而不暴露具体的订单流水。
 */
export class SovereignCreditPoolService {
  private static readonly CREDIT_TABLE = 'cf_sovereign_credits';
  private static readonly POOL_TABLE = 'cf_credit_pool_ledger';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasCreditTable = await db.schema.hasTable(this.CREDIT_TABLE);
    if (!hasCreditTable) {
      logger.info(`📦 Creating ${this.CREDIT_TABLE} table...`);
      await db.schema.createTable(this.CREDIT_TABLE, (table) => {
        table.string('tenantId', 64).primary();
        table.integer('score').notNullable();
        table.string('tier', 20).notNullable();
        table.decimal('availableCredit', 20, 2);
        table.decimal('usedCredit', 20, 2).defaultTo(0);
        table.text('zkpProof'); // 模拟零知识证明字符串
        table.timestamp('lastAssessmentDate').defaultTo(db.fn.now());
        table.timestamps(true, true);
      });
    }

    const hasPoolTable = await db.schema.hasTable(this.POOL_TABLE);
    if (!hasPoolTable) {
      logger.info(`📦 Creating ${this.POOL_TABLE} table...`);
      await db.schema.createTable(this.POOL_TABLE, (table) => {
        table.increments('id').primary();
        table.string('borrowerId', 64).notNullable();
        table.string('lenderId', 64); // 如果是点对点借贷
        table.decimal('amount', 20, 2).notNullable();
        table.decimal('interestRate', 5, 4); // 年化利率
        table.string('status', 20).defaultTo('ACTIVE'); // ACTIVE, REPAID, DEFAULT
        table.timestamp('dueDate').notNullable();
        table.timestamps(true, true);
        table.index(['borrowerId', 'status']);
      });
    }
  }

  /**
   * ZKP 隐私评估信用评分 (AGI 驱动)
   */
  static async assessCredit(tenantId: string): Promise<CreditScore> {
    logger.info(`[CreditPool] Assessing credit for tenant: ${tenantId} via ZKP-like engine`);

    // 1. 获取经营表现 (不直接暴露明细)
    const stats = await db('cf_recon_records')
      .where({ tenantId, status: 'MATCHED' })
      .select(
        db.raw('SUM(netProfit) as totalProfit'),
        db.raw('COUNT(*) as orderCount')
      )
      .first();

    // 2. AGI 信用建模 (模拟 ZKP 证明生成)
    const profit = Number(stats.totalProfit || 0);
    const orderCount = Number(stats.orderCount || 0);
    
    let score = 350; // 初始分
    score += Math.min(400, (profit / 1000) * 10); // 基于利润加分
    score += Math.min(250, orderCount * 2); // 基于单量加分

    let tier: CreditScore['tier'] = 'SILVER';
    if (score > 850) tier = 'DIAMOND';
    else if (score > 700) tier = 'PLATINUM';
    else if (score > 550) tier = 'GOLD';

    const availableCredit = (profit > 0 ? profit * 0.3 : 500) * (score / 500);

    const credit: CreditScore = {
      tenantId,
      score: Math.floor(score),
      tier,
      availableCredit: Number(availableCredit.toFixed(2)),
      lastAssessmentDate: new Date()
    };

    // 3. 持久化 (保存模拟 Proof)
    await db(this.CREDIT_TABLE)
      .insert({
        ...credit,
        zkpProof: `ZKP-CREDIT-PROOF-${Buffer.from(tenantId).toString('base64').slice(0, 10)}-${score}`,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict(['tenantId'])
      .merge();

    return credit;
  }

  /**
   * 申请微贷
   */
  static async applyLoan(tenantId: string, amount: number): Promise<boolean> {
    logger.info(`[CreditPool] Loan application: ${amount} for tenant: ${tenantId}`);

    const credit = await db(this.CREDIT_TABLE).where({ tenantId }).first();
    if (!credit || (credit.availableCredit - credit.usedCredit) < amount) {
      logger.warn(`[CreditPool] Insufficient credit for ${tenantId}`);
      return false;
    }

    // 更新额度并记录借贷
    await db.transaction(async (trx) => {
      await trx(this.CREDIT_TABLE).where({ tenantId }).increment('usedCredit', amount);
      await trx(this.POOL_TABLE).insert({
        borrowerId: tenantId,
        amount,
        interestRate: 0.08, // 8% 年化
        dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 天后到期
        created_at: new Date(),
        updated_at: new Date()
      });
    });

    return true;
  }
}
