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

export interface ComplianceCertificate {
  id?: string;
  tenant_id: string;
  order_id: string;
  certificate_type: 'ORIGIN' | 'CE' | 'FDA' | 'ROHS';
  issuing_authority_did: string;
  digital_signature: string;
  status: 'GENERATED' | 'VERIFIED' | 'REVOKED';
  valid_until: Date;
  created_at?: Date;
}

/**
 * [BIZ_TRADE_50] 动态出口管制合规证书自动化生成 (Compliance Certificate)
 * @description 自动提取订单数据并生成符合目的国要求的电子合规证书。
 */
export class ComplianceCertificateService {
  private static readonly CERT_TABLE = 'cf_compliance_certificates';

  /**
   * 为订单生成合规证书
   */
  static async generateCertificate(tenantId: string, orderId: string, type: 'ORIGIN' | 'CE' | 'FDA' | 'ROHS') {
    logger.info(`[ComplianceCert] Generating ${type} certificate for order: ${orderId}`);

    // 1. 验证订单合规扫描结果 (联动 TradeComplianceService)
    
    // 2. 构造证书数据
    const cert: ComplianceCertificate = {
      tenant_id: tenantId,
      order_id: orderId,
      certificate_type: type,
      issuing_authority_did: 'DID-GOV-COMPLIANCE-HUB',
      digital_signature: `SIG-${orderId}-${Date.now()}`, // 模拟 DID 签名
      status: 'GENERATED',
      valid_until: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1年有效
      created_at: new Date()
    };

    await db(this.CERT_TABLE).insert(cert);

    return cert;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.CERT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.CERT_TABLE} table...`);
      await db.schema.createTable(this.CERT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('order_id', 64).notNullable().index();
        table.string('certificate_type', 32).notNullable();
        table.string('issuing_authority_did', 128).notNullable();
        table.string('digital_signature', 256).notNullable();
        table.string('status', 32).defaultTo('GENERATED');
        table.timestamp('valid_until');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
