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

export interface AdCampaign {
  id: string;
  tenantId: string;
  shopId: string;
  productId: string;
  platform: 'FB' | 'TIKTOK';
  dailyBudget: number;
  cpaLimit: number;
  status: 'ACTIVE' | 'PAUSED_STOCK' | 'PAUSED_ROI';
}

/**
 * [BIZ_MKT_01] 投放-库存联动与 ROI 自动止损服务
 */
export class AdAutoService {
  private static readonly TABLE_NAME = 'cf_ad_campaigns';

  /**
   * 注册广告组
   */
  static async registerCampaign(campaign: AdCampaign): Promise<void> {
    logger.info(`[AdAuto] Registering campaign: ${campaign.id} for Product: ${campaign.productId}`);
    
    await db(this.TABLE_NAME).insert({
      id: campaign.id,
      tenant_id: campaign.tenantId,
      shop_id: campaign.shopId,
      product_id: campaign.productId,
      platform: campaign.platform,
      daily_budget: campaign.dailyBudget,
      cpa_limit: campaign.cpaLimit,
      status: campaign.status,
      created_at: new Date(),
      updated_at: new Date()
    });
  }

  /**
   * 执行自动化巡检 (由定时任务调用)
   * 1. 检查库存是否充足
   * 2. 检查 CPA 是否超标
   */
  static async performAudit(): Promise<void> {
    const activeCampaigns = await db(this.TABLE_NAME).where({ status: 'ACTIVE' });
    
    for (const campaign of activeCampaigns) {
      await this.auditCampaign(campaign);
    }
  }

  private static async auditCampaign(campaign: any): Promise<void> {
    try {
      // 1. 库存联动检查 (BIZ_MKT_01)
      const stock = await InventoryService.getSKUStock(campaign.product_id, campaign.tenant_id);
      if (stock.available_stock <= 5) {
        logger.warn(`[AdAuto] Low stock detected for campaign ${campaign.id}. Pausing ad.`);
        await this.updateStatus(campaign.id, 'PAUSED_STOCK', 'Low inventory (<= 5 units)');
        return;
      }

      // 2. ROI 止损检查 (BIZ_MKT_01)
      // 假设从 cf_pixel_logs 获取最近 24 小时的 CPA
      const recentStats = await this.getRecentStats(campaign.product_id, campaign.tenant_id);
      if (recentStats.cpa > campaign.cpa_limit) {
        logger.warn(`[AdAuto] High CPA detected for campaign ${campaign.id}: ${recentStats.cpa} > ${campaign.cpa_limit}. Pausing ad.`);
        await this.updateStatus(campaign.id, 'PAUSED_ROI', `CPA limit exceeded: ${recentStats.cpa.toFixed(2)}`);
        return;
      }
    } catch (err: any) {
      logger.error(`[AdAuto] Audit failed for campaign ${campaign.id}: ${err.message}`);
    }
  }

  private static async updateStatus(campaignId: string, status: string, reason: string): Promise<void> {
    await db(this.TABLE_NAME).where({ id: campaignId }).update({
      status,
      updated_at: new Date()
    });
    // 在实际业务中，应调用外部广告平台 API (FB/TikTok) 真正暂停广告组
    logger.info(`[AdAuto] [API_CALL] Paused campaign ${campaignId} on platform. Reason: ${reason}`);
  }

  private static async getRecentStats(productId: string, tenantId: string): Promise<{ cpa: number }> {
    // 模拟从 Pixel 数据中计算 CPA
    // 实际逻辑应为: 总支出 / 转化数
    return { cpa: Math.random() * 20 }; // 随机返回一个 CPA 用于测试
  }
}
