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

export interface LCContract {
  id?: string;
  tenant_id: string;
  order_id: string;
  amount: number;
  currency: string;
  issuing_bank_did: string;
  beneficiary_did: string;
  zkp_proof_hash: string;
  status: 'PENDING_ISSUE' | 'ISSUED' | 'NEGOTIATING' | 'HONORED' | 'EXPIRED';
  expiry_date: Date;
  created_at?: Date;
}

/**
 * [BIZ_FIN_70] 基于 ZKP 的链上隐私信用证 (Private L/C)
 * @description 利用零知识证明 (ZKP) 保护 B2B 交易中的商业机密，同时向金融机构证明交易真实性。
 */
export class SovereignPrivateLCService {
  private static readonly LC_CONTRACTS_TABLE = 'cf_private_lc_contracts';

  /**
   * 发行链上隐私信用证
   */
  static async issueLC(params: {
    tenantId: string;
    orderId: string;
    amount: number;
    currency: string;
    issuingBankDid: string;
    beneficiaryDid: string;
    expiryDate: Date;
  }): Promise<LCContract> {
    logger.info(`[PrivateLC] Issuing L/C for order ${params.orderId} from ${params.issuingBankDid} to ${params.beneficiaryDid}`);

    // 1. 生成零知识证明 (ZKP) 以证明交易真实性但不泄露敏感细节 (e.g., 供应商 ID, 利润)
    // 逻辑：通过 PrivateAuditService 生成证明
    const zkpProofHash = await PrivateAuditService.generateProof(params.tenantId, 'B2B_TRADE_VALIDITY', {
      order_id: params.orderId,
      amount: params.amount,
      currency: params.currency,
      issuing_bank_did: params.issuingBankDid,
      beneficiary_did: params.beneficiaryDid
    });

    const contract: LCContract = {
      tenant_id: params.tenantId,
      order_id: params.orderId,
      amount: params.amount,
      currency: params.currency,
      issuing_bank_did: params.issuingBankDid,
      beneficiary_did: params.beneficiaryDid,
      zkp_proof_hash: zkpProofHash,
      status: 'ISSUED',
      expiry_date: params.expiryDate,
      created_at: new Date()
    };

    // 2. 存储信用证合约
    await db(this.LC_CONTRACTS_TABLE).insert(contract);

    return contract;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.LC_CONTRACTS_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.LC_CONTRACTS_TABLE} table...`);
      await db.schema.createTable(this.LC_CONTRACTS_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('order_id', 64).notNullable().index();
        table.decimal('amount', 15, 2).notNullable();
        table.string('currency', 10).notNullable();
        table.string('issuing_bank_did', 128).notNullable();
        table.string('beneficiary_did', 128).notNullable();
        table.string('zkp_proof_hash', 128).notNullable();
        table.string('status', 32).defaultTo('PENDING_ISSUE');
        table.timestamp('expiry_date').notNullable();
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
