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

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

  constructor(private readonly em: EntityManager) {}

  // run every day at 00:03
  @Cron('3 0 * * *', {
    name: 'resetAvailableStock',
    timeZone: 'UTC',
  })
  async handleCron() {
    try {
      this.logger.debug('Starting daily inventory reset (availableStock = totalStock)');

      const inventories = await this.em.find(Inventory, {});
      if (!inventories || inventories.length === 0) {
        this.logger.debug('No inventory records found to reset');
        return;
      }

      this.logger.log(`Resetting available stock for ${inventories.length} inventory records`);

      await this.em.transactional(async em => {
        for (const inv of inventories) {
          // reload inside transaction to avoid concurrency issues
          const record = await em.findOne(Inventory, { id: inv.id });
          if (!record) continue;
          record.availableStock = record.totalStock;
          em.persist(record);
        }
        await em.flush();
      });

      this.logger.log('Daily inventory reset completed');
    } catch (err) {
      this.logger.error(`FoodStockCrone failed: ${err?.message}`, err);
    }
  }
}
