import {
  Controller,
  Get,
  Param,
  Res,
  NotFoundException,
  UseInterceptors,
  InternalServerErrorException,
  Injectable,
} from '@nestjs/common';
import { FastifyReply } from 'fastify';
import * as path from 'path';
import * as fs from 'fs';
import { Public } from '@/models/users/decorators/public-route';
import * as archiver from 'archiver';
import { ShootingRepo } from '../../repos/shooting.repo';
import { PhotoRepo } from '../../repos/photo.repo';

@Controller('shootings')
export class DownloadAllShootingPhotos {
  constructor(
    private shootingRepo: ShootingRepo,
    private photoRepo: PhotoRepo,
  ) {}

  @Public()
  @Get(':id/download-photos')
  async downloadAllPhotos(
    @Param('id') shootingId: string,
    @Res() reply: FastifyReply,
  ) {
    try {
      const shooting = await this.shootingRepo.findById(shootingId);

      if (!shooting) {
        throw new NotFoundException('Shooting introuvable');
      }

      const photos = await this.photoRepo.findByShootingId(shootingId);

      if (!photos || photos.length === 0) {
        throw new NotFoundException('Aucune photo trouvée pour ce shooting');
      }

      const zipFileName = `${shooting.name.replace(/\s+/g, '_')}_photos.zip`;
      reply.header('Content-Type', 'application/zip');
      reply.header(
        'Content-Disposition',
        `attachment; filename=${zipFileName}`,
      );

      const archive = archiver('zip', {
        zlib: { level: 5 },
      });
      archive.on('error', (err) => {
        console.error('Archive error:', err);
        throw new InternalServerErrorException(
          "Erreur lors de la création de l'archive",
        );
      });

      archive.pipe(reply.raw);

      const basePath = process.env.UPLOAD_PATH || __dirname;
      const shootingPath = path.join(basePath, `shootings/${shootingId}`);

      if (!fs.existsSync(shootingPath)) {
        throw new NotFoundException('Dossier du shooting introuvable');
      }

      for (const photo of photos) {
        const fileName = photo.url.split('/').pop();
        if (!fileName) continue;

        const filePath = path.join(shootingPath, fileName);

        if (fs.existsSync(filePath)) {
          archive.file(filePath, { name: fileName });
        } else {
          console.warn(`File not found: ${filePath}`);
        }
      }

      await archive.finalize();

      return reply;
    } catch (error) {
      console.error('Download all photos error:', error);

      if (error instanceof NotFoundException) {
        throw error;
      }

      throw new InternalServerErrorException(
        'Erreur lors du téléchargement des photos',
      );
    }
  }
}
