// tasks.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { SyncService } from '../sync/sync.service';

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

  private isRunning = false; // flag để lock

  constructor(readonly syncService: SyncService) {}

  @Cron(CronExpression.EVERY_10_MINUTES)
  async handleCron() {
    if (this.isRunning) {
      this.logger.warn('Cron job đang chạy, bỏ qua lần trigger mới.');
      return;
    }
    this.isRunning = true;
    this.logger.debug('Cron job bắt đầu...');
    try {
      await this.syncService.sync();
      this.logger.debug('Cron job hoàn tất.');
    } catch (err) {
      this.logger.error('Cron job lỗi:', err);
    } finally {
      this.isRunning = false; // unlock
    }
  }
}
