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

/**
 * [BIZ_FIN_196] 全链路营销活动盈亏平衡点实时监控 (Break-even)
 * @description 实时监控营销活动盈亏平衡点。
 */
export class CampaignHealthService {
  private static readonly MONITOR_TABLE = 'cf_campaign_health_monitors';

  /**
   * 监控营销活动健康状况
   */
  static async checkCampaignHealth(tenantId: string, campaignId: string) {
    logger.info(`[CampaignHealth] Checking health for campaign: ${campaignId} for tenant: ${tenantId}`);

    // 1. 获取广告支出和订单收入 (关联 campaignId)
    const adSpend = await db('cf_ad_stats')
      .where({ tenant_id: tenantId, campaign_id: campaignId })
      .select(db.raw('SUM(spend) as totalSpend'));

    const revenue = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, campaign_id: campaignId })
      .select(db.raw('SUM(total_amount) as totalRevenue'));

    const totalSpend = Number(adSpend[0].totalSpend || 0);
    const totalRevenue = Number(revenue[0].totalRevenue || 0);

    // 2. 估计盈亏平衡点 (Break-even ROAS)
    // 假设 30% 毛利率，Break-even ROAS = 1 / 0.3 = 3.33
    const breakEvenROAS = 3.33;
    const currentROAS = totalSpend > 0 ? totalRevenue / totalSpend : 0;

    // 3. 评估健康状况
    let status = 'HEALTHY';
    let alertMsg = 'Campaign is profitable';

    if (currentROAS < breakEvenROAS * 0.8) {
      status = 'CRITICAL';
      alertMsg = `ROAS (${currentROAS.toFixed(2)}) is below break-even point (${breakEvenROAS.toFixed(2)}). Losing money!`;
    } else if (currentROAS < breakEvenROAS) {
      status = 'WARNING';
      alertMsg = `ROAS (${currentROAS.toFixed(2)}) is near break-even. Monitor closely.`;
    }

    const healthLog = {
      id: `CH-${tenantId}-${campaignId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      campaignId,
      totalSpend: Number(totalSpend.toFixed(2)),
      totalRevenue: Number(totalRevenue.toFixed(2)),
      currentROAS: Number(currentROAS.toFixed(2)),
      breakEvenROAS: Number(breakEvenROAS.toFixed(2)),
      status,
      alertMsg,
      created_at: new Date()
    };

    // 4. 存储监控记录
    await db(this.MONITOR_TABLE)
      .insert(healthLog)
      .onConflict(['id'])
      .merge();

    return healthLog;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.MONITOR_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.MONITOR_TABLE} table...`);
      await db.schema.createTable(this.MONITOR_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('campaignId', 128).notNullable();
        table.decimal('totalSpend', 15, 2);
        table.decimal('totalRevenue', 15, 2);
        table.decimal('currentROAS', 10, 2);
        table.decimal('breakEvenROAS', 10, 2);
        table.string('status', 20); // E.g., HEALTHY, WARNING, CRITICAL
        table.text('alertMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'campaignId']);
      });
    }
  }
}
