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

export interface CarbonPledge {
  id?: string;
  tenant_id: string;
  pledge_amount: number; // kg CO2
  target_benefit: 'LOWER_FEES' | 'EXTENDED_TERMS' | 'HIGHER_CREDIT';
  status: 'PENDING' | 'ACTIVE' | 'RELEASED';
  created_at?: Date;
}

/**
 * [BIZ_TRADE_60] 自动化供应链碳配额质押建议 (Carbon Pledge)
 * @description 允许租户质押碳抵扣额度以获取业务权益。
 */
export class CarbonPledgeService {
  private static readonly PLEDGE_TABLE = 'cf_carbon_pledges';

  /**
   * 发起碳配额质押建议
   */
  static async suggestPledge(tenantId: string) {
    logger.info(`[CarbonPledge] Generating pledge suggestion for tenant: ${tenantId}`);

    // 1. 获取租户累计碳信用 (联动 CarbonCreditTradingService)
    const totalCredits = await db('cf_carbon_credit_transactions')
      .where({ tenant_id: tenantId, status: 'SETTLED' })
      .select(db.raw('SUM(credits_purchased) as totalCredits'));

    const credits = Number(totalCredits[0].totalCredits || 0);

    if (credits < 1000) {
      logger.info(`[CarbonPledge] Tenant ${tenantId} credits below pledge threshold.`);
      return null;
    }

    // 2. 构造建议质押
    const pledge: CarbonPledge = {
      tenant_id: tenantId,
      pledge_amount: credits * 0.5, // 质押 50%
      target_benefit: 'EXTENDED_TERMS',
      status: 'PENDING',
      created_at: new Date()
    };

    await db(this.PLEDGE_TABLE).insert(pledge);

    return pledge;
  }

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