import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import { ShootingRepo } from '../../repos/shooting.repo';
import { CustomerRepo } from '../../repos/customer.repo';
import { CreateShootingDTO, ShootingDTO } from '@studio-m/app-types';
import { Customer } from '../../domain/Customer';
import { assertAtLeastOneValueIsDefined } from '@/core/functions/assert';
import { Shooting } from '../../domain/Shooting';
import { ShootingMapper } from '../../mappers/shooting.mapper';
import { EventEmitter2 } from '@nestjs/event-emitter';

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

  @Post()
  async execute(@Body() body: CreateShootingDTO): Promise<ShootingDTO> {
    let customer: Customer;

    assertAtLeastOneValueIsDefined([body.customerId, body.customer]);

    if (body.customerId) {
      customer = await this.customerRepo.findById(body.customerId);
    } else {
      const newCustomer = Customer.create({
        firstname: body.customer.firstname,
        lastname: body.customer.lastname,
        email: body.customer.email,
        phone: body.customer.phone,
        address: body.customer.address,
        city: body.customer.city,
        zipcode: body.customer.zipcode,
        createdAt: new Date(),
        updatedAt: new Date(),
        allowDownload: true,
      });

      customer = await this.customerRepo.create(newCustomer);
    }

    const shootingDate = new Date(body.description);

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

    const newShooting = Shooting.create({
      name: body.name,
      description: shootingDate,
      customerId: customer.id,
      createdAt: new Date(),
      updatedAt: new Date(),
      allowDownload: body.allowDownload,
    });

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

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

    return ShootingMapper.toDTO(persistedShooting);
  }
}
