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

export interface CarbonLog {
  tenantId: string;
  productId: string;
  orderId?: string;
  category: 'SOURCING' | 'LOGISTICS' | 'PACKAGING';
  emissionsKg: number;
}

/**
 * [BIZ_TRADE_12] 绿色供应链评估与碳中和路径服务
 * @description 追踪商品全生命周期的碳足迹，提供低碳物流建议并生成 ESG 报告
 */
export class GreenSupplyChainService {
  private static readonly TABLE_NAME = 'cf_carbon_footprints';

  /**
   * 记录碳排放记录 (BIZ_TRADE_12)
   */
  static async logEmissions(params: CarbonLog): Promise<void> {
    logger.info(`[ESG] Logging ${params.emissionsKg}kg CO2 for Product ${params.productId} (${params.category})`);

    await db(this.TABLE_NAME).insert({
      tenant_id: params.tenantId,
      product_id: params.productId,
      order_id: params.orderId,
      carbon_emissions_kg: params.emissionsKg,
      category: params.category,
      created_at: new Date(),
      updated_at: new Date()
    });
  }

  /**
   * 估算物流碳排放 (BIZ_TRADE_12)
   * @description 基于运输模式、重量与距离估算
   */
  static estimateLogisticsCarbon(mode: string, weightKg: number, distanceKm: number): number {
    // 简单系数 (kg CO2 per ton-km)
    // 航空: 0.5, 海运: 0.01, 铁路: 0.02, 公路: 0.08
    let factor = 0.08;
    switch (mode) {
      case 'AIR': factor = 0.5; break;
      case 'SEA': factor = 0.01; break;
      case 'RAIL': factor = 0.02; break;
    }

    const tons = weightKg / 1000;
    return tons * distanceKm * factor;
  }

  /**
   * 生成租户 ESG 摘要报告
   */
  static async getESGSummary(tenantId: string): Promise<any> {
    const stats = await db(this.TABLE_NAME)
      .where({ tenant_id: tenantId })
      .select('category')
      .sum('carbon_emissions_kg as total')
      .groupBy('category');

    return {
      tenantId,
      totalEmissions: stats.reduce((acc, curr) => acc + Number(curr.total), 0),
      breakdown: stats,
      reportDate: new Date().toISOString()
    };
  }
}
