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

/**
 * [BIZ_FIN_165] 广告 ROAS 真实性本地归因建议 (Attribution)
 * @description 剔除自然单干扰，计算真实的广告 ROAS。
 */
export class TrueROASService {
  private static readonly ATTRIBUTION_TABLE = 'cf_true_roas_attributions';

  /**
   * 执行真实 ROAS 归因
   */
  static async attributeTrueROAS(tenantId: string, skuId: string) {
    logger.info(`[TrueROAS] Attributing ROAS for SKU: ${skuId} for tenant: ${tenantId}`);

    // 1. 获取广告支出和总营收
    const adStats = await db('cf_ad_stats')
      .where({ tenant_id: tenantId, sku_id: skuId })
      .select(db.raw('SUM(spend) as totalSpend'), db.raw('SUM(revenue) as adRevenue'));

    const totalOrders = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, productId: skuId })
      .select(db.raw('SUM(total_amount) as totalRevenue'));

    const totalSpend = Number(adStats[0].totalSpend || 0);
    const platformAdRevenue = Number(adStats[0].adRevenue || 0);
    const totalRevenue = Number(totalOrders[0].totalRevenue || 0);

    // 2. 估计自然订单营收 (总营收 - 广告营收)
    const organicRevenue = Math.max(0, totalRevenue - platformAdRevenue);
    
    // 3. 计算真实 ROAS (剔除可能的重复归因)
    const trueROAS = totalSpend > 0 ? platformAdRevenue / totalSpend : 0;
    const blendedROAS = totalSpend > 0 ? totalRevenue / totalSpend : 0;

    const attribution = {
      id: `TR-${tenantId}-${skuId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      skuId,
      totalSpend: Number(totalSpend.toFixed(2)),
      platformAdRevenue: Number(platformAdRevenue.toFixed(2)),
      organicRevenue: Number(organicRevenue.toFixed(2)),
      trueROAS: Number(trueROAS.toFixed(2)),
      blendedROAS: Number(blendedROAS.toFixed(2)),
      created_at: new Date()
    };

    // 4. 存储归因记录
    await db(this.ATTRIBUTION_TABLE)
      .insert(attribution)
      .onConflict(['id'])
      .merge();

    return attribution;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.ATTRIBUTION_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.ATTRIBUTION_TABLE} table...`);
      await db.schema.createTable(this.ATTRIBUTION_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('skuId', 128).notNullable();
        table.decimal('totalSpend', 15, 2);
        table.decimal('platformAdRevenue', 15, 2);
        table.decimal('organicRevenue', 15, 2);
        table.decimal('trueROAS', 10, 2);
        table.decimal('blendedROAS', 10, 2);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'skuId']);
      });
    }
  }
}
