import { Body, Controller, Param, Post, UseGuards } from '@nestjs/common';
import { ShootingRepo } from '../../repos/shooting.repo';
import { PhotoRepo } from '../../repos/photo.repo';
import { assertRessourceExists } from '@/core/functions/assert';
import { Shooting } from '../../domain/Shooting';
import { Photo } from '../../domain/Photo';
import { DuplicateShootingDTO } from '@studio-m/app-types';
import * as path from 'path';
import * as fs from 'fs';
import { AdminGuard } from '@/models/users/guards/admin.guard';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Controller('shootings')
export class DuplicateShooting {
  constructor(
    private readonly shootingRepo: ShootingRepo,
    private readonly photoRepo: PhotoRepo,
    private readonly eventEmitter: EventEmitter2,
  ) {}

  @UseGuards(AdminGuard)
  @Post(':id/duplicate')
  async execute(@Param('id') id: string, @Body() body: DuplicateShootingDTO) {
    const persistedShooting = await this.shootingRepo.findById(id);

    assertRessourceExists(persistedShooting);

    const newShooting = Shooting.create({
      customerId: body.customerId || persistedShooting.customerId,
      createdAt: new Date(),
      updatedAt: new Date(),
      description: persistedShooting.description,
      name: `${persistedShooting.name} (copie)`,
    });

    const savedShooting = await this.shootingRepo.create(newShooting);

    const originalPhotos = await this.photoRepo.findByShootingId(id);

    const newUploadPath = path.join(
      process.env.UPLOAD_PATH,
      `shootings/${savedShooting.id}`,
    );
    fs.mkdirSync(newUploadPath, { recursive: true });

    const newPhotos = await Promise.all(
      originalPhotos.map(async (originalPhoto, index) => {
        const originalFilePath = path.join(
          process.env.UPLOAD_PATH,
          `shootings/${id}`,
          originalPhoto.filename,
        );
        const newFilename = `${Date.now()}-${originalPhoto.filename}`;
        const newFilePath = path.join(newUploadPath, newFilename);

        try {
          if (!fs.existsSync(originalFilePath)) {
            console.error(
              `Le fichier source n'existe pas: ${originalFilePath}`,
            );
            throw new Error(
              `Le fichier source n'existe pas: ${originalFilePath}`,
            );
          }

          await fs.promises.copyFile(originalFilePath, newFilePath);

          const newPhoto = Photo.create({
            filename: newFilename,
            originalname: originalPhoto.originalname,
            path: newFilePath,
            shootingId: savedShooting.id,
            createdAt: new Date(),
            updatedAt: new Date(),
            order: index + 1,
          });

          return newPhoto;
        } catch (error) {
          console.error(`Erreur lors de la copie du fichier: ${error.message}`);
          throw error;
        }
      }),
    );

    await this.photoRepo.createMany(newPhotos);

    this.eventEmitter.emit('shooting.created', savedShooting);

    return {
      message: 'Shooting dupliqué avec succès',
      shooting: savedShooting,
      photos: newPhotos,
    };
  }
}
