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

export interface CarbonFootprint {
  id?: string;
  tenant_id: string;
  order_id?: string;
  product_id: string;
  total_co2: number; // kg
  logistics_emissions: number;
  production_emissions: number;
  packaging_emissions: number;
  offset_cost: number;
  status: 'ESTIMATED' | 'OFFSET_PENDING' | 'OFFSET_COMPLETED';
  created_at?: Date;
}

export interface ReductionPath {
  strategy: string;
  potentialReduction: number; // %
  estimatedCost: number;
  timeframe: 'SHORT_TERM' | 'MEDIUM_TERM' | 'LONG_TERM';
}

/**
 * [BIZ_LOG_40] 绿色供应链碳足迹核算与抵扣 (Green Supply Chain Enhanced)
 * @description 计算物流与生产全链路碳足迹，提供减排建议与订单级碳抵扣。
 */
export class GreenSupplyChainService {
  private static readonly FOOTPRINT_TABLE = 'cf_carbon_footprints';

  /**
   * 估算并记录订单/商品碳足迹
   */
  static async recordFootprint(params: {
    tenantId: string;
    orderId?: string;
    productId: string;
    logisticsDetails: { distance: number; mode: 'AIR' | 'SEA' | 'LAND' | 'RAIL' };
    productionDetails: { weight: number };
  }): Promise<CarbonFootprint> {
    logger.info(`[GreenSC] Recording carbon footprint for product: ${params.productId} in order: ${params.orderId}`);

    // 1. 模拟物流碳足迹计算
    const logisticsEmissions = params.logisticsDetails.distance * (params.logisticsDetails.mode === 'AIR' ? 0.5 : 0.1);

    // 2. 模拟生产碳足迹计算
    const productionEmissions = params.productionDetails.weight * 2.5;

    // 3. 模拟包装碳足迹
    const packagingEmissions = 0.5;

    const totalCO2 = logisticsEmissions + productionEmissions + packagingEmissions;
    const offsetCost = (totalCO2 / 1000) * 25.0; // $25 per ton

    const footprint: CarbonFootprint = {
      tenant_id: params.tenantId,
      order_id: params.orderId,
      product_id: params.productId,
      total_co2: Number(totalCO2.toFixed(2)),
      logistics_emissions: Number(logisticsEmissions.toFixed(2)),
      production_emissions: Number(productionEmissions.toFixed(2)),
      packaging_emissions: Number(packagingEmissions.toFixed(2)),
      offset_cost: Number(offsetCost.toFixed(2)),
      status: 'ESTIMATED',
      created_at: new Date()
    };

    await db(this.FOOTPRINT_TABLE).insert(footprint);

    return footprint;
  }

  /**
   * 生成碳中和路径建议
   */
  static async suggestReductionPath(productId: string): Promise<ReductionPath[]> {
    logger.info(`[GreenSC] Generating reduction paths for ${productId}`);

    return [
      {
        strategy: 'Switch to Sea Freight (LCL) instead of Air Freight',
        potentialReduction: 0.75,
        estimatedCost: -200,
        timeframe: 'SHORT_TERM'
      },
      {
        strategy: 'Use Recycled Cardboard for Packaging',
        potentialReduction: 0.15,
        estimatedCost: 50,
        timeframe: 'SHORT_TERM'
      },
      {
        strategy: 'Transition to Renewable Energy in Factory',
        potentialReduction: 0.45,
        estimatedCost: 5000,
        timeframe: 'LONG_TERM'
      }
    ];
  }

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