import { Controller, Injectable, Put } from '@nestjs/common';
import { Body } from '@nestjs/common';
import { PhotoRepo } from '../../repos/photo.repo';
import { ShootingRepo } from '../../repos/shooting.repo';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { assertRessourceExists } from '@/core/functions/assert';
import { UpdatePhotosOrderDTO } from '@studio-m/app-types';

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

  @Put('/order')
  async execute(@Body() body: UpdatePhotosOrderDTO) {
    const shooting = await this.shootingRepo.findById(body.shootingId);

    assertRessourceExists(shooting);

    for (const { id, order } of body.photoOrders) {
      const photo = shooting.photos.find((p) => p.id === id);

      if (photo) {
        photo.order = order;
        await this.photoRepo.update(photo);
      }
    }

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

    return {
      message: 'Ordre des photos mis à jour',
    };
  }
}
