import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { EntityManager } from '@mikro-orm/postgresql';
import { Restaurant } from '../entities/restaurant.entity';

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

    constructor(private readonly em: EntityManager) { }

    // run every day at 03:00 (3:00 AM)
    @Cron('0 3 * * *', {
        name: 'deactivateExpiredSubscriptions',
        timeZone: 'UTC',
    })
    async handleCron() {
        try {
            this.logger.debug('Starting daily subscription expiration check');

            // Get current date
            const now = new Date();

            // Find restaurants where subscription has expired and they're still active
            const expiredRestaurants = await this.em.find(Restaurant, {
                subscriptionEndDate: { $lt: now },
                isActive: true,
            });

            if (!expiredRestaurants || expiredRestaurants.length === 0) {
                this.logger.debug('No restaurants with expired subscriptions found');
                return;
            }

            this.logger.log(`Found ${expiredRestaurants.length} restaurants with expired subscriptions`);

            // Deactivate expired restaurants
            for (const restaurant of expiredRestaurants) {
                restaurant.isActive = false;
            }

            // Persist all changes
            await this.em.persistAndFlush(expiredRestaurants);

            this.logger.log(`Successfully deactivated ${expiredRestaurants.length} restaurants with expired subscriptions`);
        } catch (err) {
            this.logger.error(`RestaurantCrone failed: ${err?.message}`, err);
        }
    }
}
