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

/**
 * [BIZ_FIN_170] 周期性亏损 SKU 淘汰建议报告 (Killer)
 * @description 识别利润黑洞，评估 SKU 效率，建议淘汰亏损 SKU。
 */
export class SKUEfficiencyService {
  private static readonly EFFICIENCY_TABLE = 'cf_sku_efficiency_reports';

  /**
   * 评估指定租户的所有 SKU 效率
   */
  static async auditTenantSKUEfficiency(tenantId: string) {
    logger.info(`[SKUEfficiency] Auditing SKU efficiency for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的所有对账记录
    const reports = await db('cf_recon_records')
      .join('cf_consumer_orders', 'cf_recon_records.orderId', '=', 'cf_consumer_orders.id')
      .where('cf_recon_records.tenantId', tenantId)
      .andWhere('cf_recon_records.created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        'cf_consumer_orders.productId as skuId',
        db.raw('SUM(cf_recon_records.netProfit) as totalProfit'),
        db.raw('COUNT(cf_recon_records.id) as orderCount'),
        db.raw('AVG(cf_recon_records.netProfit) as avgProfitPerOrder')
      )
      .groupBy('cf_consumer_orders.productId');

    const efficiencyReports = [];

    for (const report of reports) {
      const { skuId, totalProfit, orderCount, avgProfitPerOrder } = report;
      
      // 2. 识别利润黑洞 (亏损或极低利润)
      let suggestion = 'RETAIN';
      let reason = 'Healthy profit margin';

      if (totalProfit < 0) {
        suggestion = 'ELIMINATE';
        reason = `Cumulative loss of ${Math.abs(totalProfit).toFixed(2)} in 30 days`;
      } else if (avgProfitPerOrder < 2.0 && orderCount > 10) {
        suggestion = 'REVIEW';
        reason = 'Low efficiency (profit < $2/order)';
      }

      const efficiencyReport = {
        id: `EFF-${tenantId}-${skuId}-${new Date().toISOString().split('T')[0]}`,
        tenantId,
        skuId,
        totalProfit: Number(totalProfit),
        orderCount: Number(orderCount),
        avgProfitPerOrder: Number(avgProfitPerOrder),
        suggestion,
        reason,
        created_at: new Date()
      };

      efficiencyReports.push(efficiencyReport);

      // 3. 存储建议
      await db(this.EFFICIENCY_TABLE)
        .insert(efficiencyReport)
        .onConflict(['id'])
        .merge();
    }

    return efficiencyReports;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.EFFICIENCY_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.EFFICIENCY_TABLE} table...`);
      await db.schema.createTable(this.EFFICIENCY_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('skuId', 128).notNullable();
        table.decimal('totalProfit', 15, 2);
        table.integer('orderCount');
        table.decimal('avgProfitPerOrder', 15, 2);
        table.string('suggestion', 20); // E.g., EILIMINATE, REVIEW, RETAIN
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'skuId']);
      });
    }
  }
}
