import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { UsersService } from '../../users/services/users.service';
import { MetaAdsService } from '../../meta-ads/services/meta-ads.service';
import { AnalyticsService } from '../../analytics/services/analytics.service';
import { NotificationService } from '../../notifications/services/notification.service';
import { MetaLevel } from '../../meta-ads/dto/fetch-insights.dto';
import { RuleEngineService } from './rule-engine.service';

@Injectable()
export class AutomationService {
  private readonly logger = new Logger(AutomationService.name);

  constructor(
    private readonly usersService: UsersService,
    private readonly metaAdsService: MetaAdsService,
    private readonly analyticsService: AnalyticsService,
    private readonly notificationService: NotificationService,
    private readonly ruleEngineService: RuleEngineService,
  ) {
    this.logger.log('AutomationService initialized with Cron support | تم تهيئة خدمة الأتمتة');
  }

  /**
   * Daily Ads Health Check Cron Job
   * فحص صحة الإعلانات يومياً
   * Runs at midnight every day
   */
  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async handleDailyHealthCheck() {
    this.logger.log('Starting daily ad health check cron job | بدء فحص صحة الإعلانات اليومي');
    
    try {
      const users = await this.usersService.findAll();
      this.logger.log(`Scanning ${users.length} users for ad performance...`);

      for (const user of users) {
        await this.scanUserPerformance(user.id, user.subscriptionTier, user.fcmToken);
      }
      
      this.logger.log('Daily ad health check completed | اكتمل فحص صحة الإعلانات');
    } catch (error) {
      this.logger.error(`Cron Job Failed: ${error.message}`);
    }
  }

  private async scanUserPerformance(userId: string, tier: string, fcmToken?: string) {
    try {
      this.logger.log(`Processing automation rules for user ${userId}...`);
      
      // 1. Process user-defined rules
      await this.ruleEngineService.processActiveRules('meta');

      // 2. Smart Health Check (AI Heuristics)
      const accounts = await this.metaAdsService.getConnectedAccounts(userId);
      for (const account of accounts) {
        const insights = await this.metaAdsService.fetchInsights({
          userId,
          adAccountId: account.externalAdAccountId,
          level: MetaLevel.CAMPAIGN,
        });

        for (const item of insights) {
          const isCampaignActive = item.status === 'ACTIVE' || item.status === 'ENABLED';
          const hasAnalysis = await this.analyticsService.hasAnyAnalysis(item.campaignId);

          if (!hasAnalysis) {
            if (isCampaignActive && (item.ctr < 1.0 || item.cpc > 2.0)) {
               await this.performAiAnalysisAndNotify(item, tier, userId, fcmToken);
            } else if (!isCampaignActive) {
               await this.performAiAnalysisAndNotify(item, tier, userId, fcmToken);
            }
          }
        }
      }
    } catch (error) {
      this.logger.warn(`Failed to scan performance for user ${userId}: ${error.message}`);
    }
  }

  private async performAiAnalysisAndNotify(item: any, tier: string, userId: string, fcmToken?: string) {
    try {
      this.logger.log(`Running AI analysis for campaign: ${item.campaignName}`);
      
      const analysis = await this.analyticsService.analyzeVisual(
        item.imageUrl || '',
        item.adCopy,
        item,
        tier,
        item.campaignId
      );

      // notify if recommendation is critical
      if (analysis.includes('إيقاف') || analysis.includes('Stop') || analysis.includes('Poor') || analysis.includes('ضعيف')) {
        const alertMsg = `⚠️ تنبيه من SaaS Pro:\nحملة "${item.campaignName}" تعاني من ضعف أداء.\n\nتوصية AI: ${analysis.substring(0, 100)}...`;
        await this.notificationService.send(alertMsg, ['telegram', 'fcm'], { fcmToken });
        this.logger.log(`Alert sent for campaign ${item.campaignId}`);
      }
    } catch (e) {
      this.logger.error(`AI Analysis/Notification failed for ${item.campaignId}: ${e.message}`);
    }
  }
}
