import {
  BadRequestException,
  Body,
  Controller,
  Put,
} from '@nestjs/common';
import { ShootingRepo } from '../../repos/shooting.repo';
import { UpdateShootingDTO } from '@studio-m/app-types';
import { assertRessourceExists } from '@/core/functions/assert';
import { ShootingMapper } from '../../mappers/shooting.mapper';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Controller('shootings')
export class UpdateShooting {
  constructor(
    private shootingRepo: ShootingRepo,
    private eventEmitter: EventEmitter2,
  ) {}

  @Put(':id')
  async execute(@Body() body: UpdateShootingDTO) {
    const persistedShooting = await this.shootingRepo.findById(body.id);

    assertRessourceExists(persistedShooting);

    if (body?.name) {
      persistedShooting.name = body.name;
    }

    if (body?.description) {
      const shootingDate = new Date(body.description);

      if (isNaN(shootingDate.getTime())) {
        throw new BadRequestException('Invalid shooting date format');
      }

      persistedShooting.description = shootingDate;
    }

    if (body?.allowDownload !== undefined) {
      persistedShooting.allowDownload = body.allowDownload;
    }

    if (body?.shareMessage) {
      persistedShooting.shareMessage = body.shareMessage;
    }

    if (body?.masonryMode !== undefined) {
      persistedShooting.masonryMode = body.masonryMode;
    }

    const updatedShooting = await this.shootingRepo.update(persistedShooting);

    this.eventEmitter.emit('shooting.updated', updatedShooting);

    return ShootingMapper.toDTO(updatedShooting);
  }
}
