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

/**
 * [BIZ_FIN_184] 基于用户 LTV 的营销成本上限建议 (CAC)
 * @description 根据 LTV 预测，指导广告投放的 CAC (Customer Acquisition Cost) 上限。
 */
export class CACThresholdService {
  private static readonly THRESHOLD_TABLE = 'cf_cac_threshold_recommendations';

  /**
   * 生成 CAC 建议上限
   */
  static async recommendCACThreshold(tenantId: string) {
    logger.info(`[CACThreshold] Recommending CAC threshold for tenant: ${tenantId}`);

    // 1. 获取过去 180 天的用户平均订单价值 (AOV) 和复购率 (Retention)
    const stats = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 180 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('AVG(total_amount) as aov'),
        db.raw('COUNT(id) / COUNT(DISTINCT customer_id) as ordersPerCustomer')
      );

    const aov = Number(stats[0].aov || 0);
    const ordersPerCustomer = Number(stats[0].ordersPerCustomer || 1);

    // 2. 估计 LTV (Life Time Value) 和 CAC 上限
    // 公式：LTV = AOV * ordersPerCustomer * margin
    const margin = 0.3; // 假设 30% 平均毛利
    const estimatedLTV = aov * ordersPerCustomer * margin;

    // 建议 CAC 上限为 LTV 的 30% (确保盈利)
    const recommendedCAC = estimatedLTV * 0.3;

    const recommendation = {
      id: `CAC-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      estimatedLTV: Number(estimatedLTV.toFixed(2)),
      recommendedCAC: Number(recommendedCAC.toFixed(2)),
      status: 'UPDATED',
      created_at: new Date()
    };

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

    return recommendation;
  }

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