import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { WhatsappService } from '../whatsapp/whatsapp.service';
import { differenceInDays } from 'date-fns';

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

  constructor(
    private prisma: PrismaService,
    private whatsapp: WhatsappService,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_9AM)
  async handleDailyAutomation() {
    this.logger.log('Running Daily Follow-up Automation...');
    
    await Promise.all([
      this.processPhase1Nudges(),
      this.processEscalations(),
    ]);
  }

  private async processPhase1Nudges() {
    const leads = await this.prisma.client.findMany({
      where: { status: 'LEAD' },
      include: { user: true },
    });

    for (const lead of leads) {
      const age = differenceInDays(new Date(), lead.createdAt);
      
      let message = '';
      if (age === 1) message = `Hi ${lead.name}, thanks for inquiring with Ignosi! Here is a quick intro to our services.`;
      else if (age === 2) message = `Hi ${lead.name}, did you know that our CRM can increase your sales by 30%? Check this video.`;
      else if (age === 3) message = `Hi ${lead.name}, here is what our customers say about us. [Testimonial Link]`;
      else if (age === 5) message = `Still looking for a solution, ${lead.name}? We have a special offer for you today.`;
      else if (age === 7) message = `Final follow-up, ${lead.name}. Would you like a free demo this week?`;

      if (message && lead.phone) {
        this.logger.log(`Triggering Day ${age} nudge for ${lead.name}`);
        // await this.whatsapp.sendInternalMessage(lead.phone, message);
      }
    }
  }

  private async processEscalations() {
    // Find opportunities where a demo has been scheduled but not yet done for 10+ days
    const staleDemoOpps = await this.prisma.opportunity.findMany({
      where: {
        isDemoDone: false,
        stage: { in: ['QUALIFIED', 'POTENTIAL'] },
        updatedAt: { lte: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000) },
      },
      include: {
        user: { include: { manager: true } },
        client: true,
      },
    });

    for (const opp of staleDemoOpps) {
      if (opp.user?.manager?.email) {
        this.logger.warn(`Escalating stale demo: ${opp.title} for user ${opp.user.name}`);
        // Send alert to manager via Email/WhatsApp
      }
    }
  }
}
