import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PrismaService } from 'src/prisma/prisma.service';
import { StorageService } from 'src/storage/storage.service';

@Injectable()
export class TempCleanupService {
  constructor(
    private prisma: PrismaService,
    private storage: StorageService,
  ) {}

  @Cron(CronExpression.EVERY_HOUR)
  async cleanupStaleTempFiles() {
    const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);

    const stale = await this.prisma.tempPhoto.findMany({
      where: { createdAt: { lt: oneHourAgo } },
    });

    for (const temp of stale) {
      await this.storage.deleteFile(temp.url);
      await this.prisma.tempPhoto.delete({ where: { id: temp.id } });
    }

    console.log(`Cleaned up ${stale.length} stale temp photos`);
  }
}