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

@Injectable()
export class ShopPlanCronService {
  private readonly logger = new Logger(ShopPlanCronService.name);
  constructor(private readonly prisma: PrismaService) {}

  @Cron(CronExpression.EVERY_HOUR)
  async tick() {
    const now = new Date();
    try {
      const basic = await this.prisma.plan.findUnique({
        where: { code: 'BASIC' },
        select: { id: true },
      });
      if (!basic) {
        this.logger.warn('BASIC plan not found; skipping plan expiry job.');
        return;
      }

      // Apply scheduled downgrade (paid → free at end-of-cycle).
      const scheduled = await this.prisma.adminSubscription.updateMany({
        where: {
          scheduledPlanCode: 'BASIC',
          scheduledPlanAt: { lte: now },
        },
        data: {
          planId: basic.id,
          planExpiresAt: null,
          scheduledPlanCode: null,
          scheduledPlanAt: null,
        },
      });

      // Auto-downgrade any expired paid plan to BASIC (safety net).
      const expired = await this.prisma.adminSubscription.updateMany({
        where: {
          planExpiresAt: { not: null, lte: now },
          plan: { priceMonthly: { gt: 0 } },
        },
        data: {
          planId: basic.id,
          planExpiresAt: null,
          scheduledPlanCode: null,
          scheduledPlanAt: null,
        },
      });

      if (scheduled.count || expired.count) {
        this.logger.log(
          `plan tick: scheduledApplied=${scheduled.count} expiredDowngraded=${expired.count}`,
        );
      }
    } catch (e: any) {
      this.logger.error(`plan tick failed: ${e?.message ?? e}`, e?.stack);
    }
  }
}
