import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PrismaService } from '../../prisma/prisma.service';

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

  constructor(private readonly prisma: PrismaService) {}

  /**
   * Runs daily at midnight to check subscription and trial expiries and send reminders.
   */
  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async handleSubscriptionExpiryCheck() {
    this.logger.log('Starting daily subscription expiry and reminder check...');
    const now = new Date();

    // 1. Process Expiring Trials
    const trials = await this.prisma.business.findMany({
      where: {
        subscriptionStatus: 'TRIAL',
        trialEnd: { not: null },
      },
    });

    for (const business of trials) {
      if (business.trialEnd && now > business.trialEnd) {
        // Expired
        await this.prisma.business.update({
          where: { id: business.id },
          data: { subscriptionStatus: 'EXPIRED', lastReminderSent: 99 },
        });
        this.logger.log(`Business ${business.name} (${business.id}) trial has expired.`);
        this.sendWhatsAppNotification(business.contactPhone || '', 'expired');
      } else if (business.trialEnd) {
        const diffTime = business.trialEnd.getTime() - now.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays === 7 && business.lastReminderSent < 7) {
          await this.prisma.business.update({
            where: { id: business.id },
            data: { lastReminderSent: 7 },
          });
          this.sendWhatsAppNotification(business.contactPhone || '', '7_days');
        } else if (diffDays === 3 && business.lastReminderSent < 3) {
          await this.prisma.business.update({
            where: { id: business.id },
            data: { lastReminderSent: 3 },
          });
          this.sendWhatsAppNotification(business.contactPhone || '', '3_days');
        } else if (diffDays === 1 && business.lastReminderSent < 1) {
          await this.prisma.business.update({
            where: { id: business.id },
            data: { lastReminderSent: 1 },
          });
          this.sendWhatsAppNotification(business.contactPhone || '', '1_day');
        }
      }
    }

    // 2. Process Expiring Paid Subscriptions
    const activeSubs = await this.prisma.business.findMany({
      where: {
        subscriptionStatus: 'ACTIVE',
        subscriptionEnd: { not: null },
      },
    });

    for (const business of activeSubs) {
      if (business.subscriptionEnd && now > business.subscriptionEnd) {
        // Expired
        await this.prisma.business.update({
          where: { id: business.id },
          data: { subscriptionStatus: 'EXPIRED', lastReminderSent: 99 },
        });
        this.logger.log(`Business ${business.name} (${business.id}) subscription has expired.`);
        this.sendWhatsAppNotification(business.contactPhone || '', 'expired');
      } else if (business.subscriptionEnd) {
        const diffTime = business.subscriptionEnd.getTime() - now.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays === 7 && business.lastReminderSent < 7) {
          await this.prisma.business.update({
            where: { id: business.id },
            data: { lastReminderSent: 7 },
          });
          this.sendWhatsAppNotification(business.contactPhone || '', '7_days_subscription');
        } else if (diffDays === 3 && business.lastReminderSent < 3) {
          await this.prisma.business.update({
            where: { id: business.id },
            data: { lastReminderSent: 3 },
          });
          this.sendWhatsAppNotification(business.contactPhone || '', '3_days_subscription');
        } else if (diffDays === 1 && business.lastReminderSent < 1) {
          await this.prisma.business.update({
            where: { id: business.id },
            data: { lastReminderSent: 1 },
          });
          this.sendWhatsAppNotification(business.contactPhone || '', '1_day_subscription');
        }
      }
    }
  }

  private sendWhatsAppNotification(phone: string, template: string) {
    if (!phone) return;
    this.logger.log(`[MOCK NOTIFICATION] Sent subscription status alert '${template}' to ${phone}`);
    // Integrates with WhatsApp Module to dispatch real message when available.
  }
}
