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

export interface InsurancePolicy {
  id?: string;
  tenant_id: string;
  order_id: string;
  provider_did: string;
  premium_amount: number;
  coverage_amount: number;
  status: 'SUGGESTED' | 'ACTIVE' | 'EXPIRED' | 'CLAIMED';
  policy_details_json: string;
  created_at?: Date;
}

/**
 * [BIZ_FIN_80] 跨主权贸易信用保险自动投保建议 (Trade Insurance)
 * @description 针对高价值跨国订单，基于风险评分自动建议投保方案。
 */
export class TradeInsuranceService {
  private static readonly INSURANCE_TABLE = 'cf_trade_insurance_policies';

  /**
   * 生成订单投保建议
   */
  static async suggestPolicy(tenantId: string, orderId: string) {
    logger.info(`[TradeInsurance] Generating insurance suggestion for order: ${orderId}`);

    // 1. 获取订单与供应商风险数据
    const order = await db('cf_consumer_orders').where({ tenant_id: tenantId, order_id: orderId }).first();
    if (!order) return null;

    // 联动 SupplierRiskRadar 获取评分 (模拟)
    const riskScore = 45; // 0-100, 越高越危险
    const orderValue = Number(order.total_amount);

    // 2. 只有高价值或高风险订单才建议投保
    if (orderValue < 1000 && riskScore < 60) {
      logger.info(`[TradeInsurance] Order ${orderId} value/risk below threshold. Skipping insurance.`);
      return null;
    }

    // 3. 构造建议保单
    const premium = orderValue * 0.02; // 2% 保费
    const policy: InsurancePolicy = {
      tenant_id: tenantId,
      order_id: orderId,
      provider_did: 'DID-INSURE-GLOBAL-001',
      premium_amount: Number(premium.toFixed(2)),
      coverage_amount: orderValue,
      status: 'SUGGESTED',
      policy_details_json: JSON.stringify({
        coverage_types: ['CARGO_LOSS', 'PAYMENT_DEFAULT'],
        risk_score_at_issue: riskScore
      }),
      created_at: new Date()
    };

    await db(this.INSURANCE_TABLE).insert(policy);

    return policy;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.INSURANCE_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.INSURANCE_TABLE} table...`);
      await db.schema.createTable(this.INSURANCE_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('order_id', 64).notNullable().index();
        table.string('provider_did', 128).notNullable();
        table.decimal('premium_amount', 15, 2);
        table.decimal('coverage_amount', 15, 2);
        table.string('status', 32).defaultTo('SUGGESTED');
        table.text('policy_details_json');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
