import { Body, Controller, Delete } from '@nestjs/common';
import { PhotoRepo } from '../../repos/photo.repo';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Photo } from '../../domain/Photo';
import { ShootingRepo } from '../../repos/shooting.repo';

export class DeletePhotosDTO {
  photoIds: { id: string }[];
}

@Controller('photos')
export class DeletePhotos {
  constructor(
    private photoRepo: PhotoRepo,
    private eventEmitter: EventEmitter2,
    private shootingRepo: ShootingRepo,
  ) {}

  @Delete()
  async execute(@Body() body: DeletePhotosDTO): Promise<{}> {
    const photos: Photo[] = await this.photoRepo.findMany(
      body.photoIds.map((photo) => photo.id),
    );

    const existingPhotos = photos.filter(
      (photo): photo is Photo => photo !== null,
    );

    if (existingPhotos.length === 0) {
      return;
    }

    await this.photoRepo.deleteMany(existingPhotos.map((photo) => photo.id));

    const shootingId = existingPhotos[0]?.shootingId;

    existingPhotos.forEach((photo) => {
      console.log(`Émission de l'événement photo.deleted pour la photo ${photo.id}`);
      this.eventEmitter.emit('photo.deleted', photo);
    });

    if (shootingId) {
      const shooting = await this.shootingRepo.findById(shootingId);

      if (shooting) {
        console.log(`Émission de l'événement shooting.updated pour le shooting ${shooting.id} après suppression de photos`);
        this.eventEmitter.emit('shooting.updated', shooting);
      }
    }

    return {};
  }
}
