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

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

    constructor(private readonly trendsService: TrendsService) {}

    /**
     * Thu thập mỗi 2 giờ
     */
    @Cron('0 */2 * * *')
    async scheduledCollection() {
        //clear before
        this.logger.log('🧹 Running daily cleanup...');
        const deleted = await this.trendsService.cleanupOldTrends(2);
        this.logger.log(`🧹 Cleanup done: removed ${deleted} old trends`);

        if (this.isCollecting) {
            this.logger.warn('Previous collection still running — skipping');
            return;
        }

        this.isCollecting = true;
        this.logger.log('⏰ Scheduled collection starting...');

        try {
            const result = await this.trendsService.collectAndStore();
            this.logger.log(
                `⏰ Scheduled collection done: ${result.stats.afterDedup} items in ${result.stats.durationMs}ms`,
            );
        } catch (error) {
            this.logger.error(`⏰ Scheduled collection failed: ${error.message}`);
        } finally {
            this.isCollecting = false;
        }
    }

    /**
     * Cleanup mỗi ngày lúc 3h sáng
     */
    @Cron('0 3 * * *')
    async scheduledCleanup() {
        this.logger.log('🧹 Running daily cleanup...');
        const deleted = await this.trendsService.cleanupOldTrends(3);
        this.logger.log(`🧹 Cleanup done: removed ${deleted} old trends`);
    }

    /**
     * Thu thập lần đầu khi app start (sau 10s delay)
     */
    async onApplicationBootstrap() {
        setTimeout(async () => {
            this.logger.log('🚀 Initial collection on startup...');
            try {
                await this.scheduledCollection();
            } catch (error) {
                this.logger.error(`Initial collection failed: ${error.message}`);
            }
        }, 10_000);
    }
}
