import { Request, Response } from 'express';
import { AdOpsService } from '../../domains/Marketing/AdOpsService';
import { AuditService } from '../../services/AuditService';

/**
 * [BIZ_MKT_20] AGI 广告管家控制器
 */
export class AdOpsController {
  /**
   * 获取所有广告计划
   */
  static async getCampaigns(req: Request, res: Response) {
    const { tenantId } = (req as any).traceContext;
    const { platform } = req.query;

    try {
      const campaigns = await AdOpsService.getCampaigns(tenantId, platform as string);
      res.json({ success: true, data: campaigns });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 同步第三方平台数据
   */
  static async syncCampaigns(req: Request, res: Response) {
    const { tenantId, shopId, traceId, userId } = (req as any).traceContext;
    const { platform } = req.body;

    try {
      await AdOpsService.syncPlatformData(tenantId, platform || 'FACEBOOK');
      
      await AuditService.log({
        tenantId,
        shopId,
        traceId,
        userId,
        module: 'MARKETING',
        action: 'AD_CAMPAIGN_SYNC',
        resourceType: 'ad_campaign',
        resourceId: platform,
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, message: `Syncing ${platform} data completed` });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * AGI 自动调优预算
   */
  static async optimizeBudget(req: Request, res: Response) {
    const { tenantId, shopId, traceId, userId } = (req as any).traceContext;
    const { campaignId } = req.params;

    try {
      const result = await AdOpsService.autoOptimizeBudget(tenantId, campaignId as string);
      
      await AuditService.log({
        tenantId,
        shopId,
        traceId,
        userId,
        module: 'MARKETING',
        action: 'AD_BUDGET_OPTIMIZE',
        resourceType: 'ad_campaign',
        resourceId: campaignId as string,
        afterSnapshot: result,
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: result });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }
}
