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

/**
 * [BIZ_FIN_177] 多渠道广告支出预算分配建议 (Ad Budget)
 * @description 基于 SKU 级边缘毛利和实时 ROAS 建议预算分配。
 */
export class AdOptimizerService {
  private static readonly OPTIMIZER_TABLE = 'cf_ad_budget_optimizations';

  /**
   * 生成预算优化建议
   */
  static async optimizeAdBudget(tenantId: string) {
    logger.info(`[AdOptimizer] Optimizing ad budget for tenant: ${tenantId}`);

    // 1. 获取过去 7 天的广告 ROI 和订单毛利数据
    const adStats = await db('cf_ad_stats')
      .where({ tenant_id: tenantId })
      .andWhere('date', '>=', new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))
      .select('platform', 'sku_id', 'spend', 'revenue', 'roas');

    const optimizations = [];

    for (const stat of adStats) {
      const { platform, sku_id, spend, revenue, roas } = stat;
      
      // 2. 评估优化建议
      let suggestion = 'MAINTAIN';
      let reason = 'ROAS is within target range';

      if (roas > 5.0) {
        suggestion = 'INCREASE';
        reason = `High performance (ROAS: ${roas.toFixed(2)}). Scale up budget.`;
      } else if (roas < 1.5) {
        suggestion = 'DECREASE';
        reason = `Low performance (ROAS: ${roas.toFixed(2)}). Cut budget to protect margin.`;
      }

      const opt = {
        id: `AO-${tenantId}-${platform}-${sku_id}-${new Date().toISOString().split('T')[0]}`,
        tenantId,
        platform,
        skuId: sku_id,
        currentSpend: Number(spend),
        currentROAS: Number(roas),
        suggestion,
        reason,
        created_at: new Date()
      };

      optimizations.push(opt);

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

    return optimizations;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.OPTIMIZER_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.OPTIMIZER_TABLE} table...`);
      await db.schema.createTable(this.OPTIMIZER_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('platform', 64).notNullable();
        table.string('skuId', 128).notNullable();
        table.decimal('currentSpend', 15, 2);
        table.decimal('currentROAS', 10, 2);
        table.string('suggestion', 20); // E.g., INCREASE, DECREASE, MAINTAIN
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'platform']);
      });
    }
  }
}
