import { Body, Controller, ForbiddenException, Post } from '@nestjs/common';
import { SearchShootingDTO } from '@studio-m/app-types';
import { ShootingRepo } from '../../repos/shooting.repo';
import { ShootingMapper } from '../../mappers/shooting.mapper';
import { Public } from '@/models/users/decorators/public-route';
import { CurrentUser } from '@/models/users/decorators/current-user';
import { User } from '@/models/users/domain/user';

@Controller('shootings/search')
export class GetShootings {
  constructor(private shootingRepo: ShootingRepo) {}

  @Public()
  @Post()
  async execute(
    @Body() body: SearchShootingDTO = {},
    @CurrentUser() currentUser: User,
  ) {
    const hasCustomerId =
      Array.isArray(body?.customerIds) && body.customerIds.some(Boolean);

    if (!currentUser && !hasCustomerId) {
      throw new ForbiddenException("Vous n'êtes pas autorisé à faire cela");
    }

    const shootings = await this.shootingRepo.search(body);

    const items = shootings.map((shooting) =>
      ShootingMapper.toDTO(shooting, { includeCustomer: !!currentUser }),
    );

    return { items };
  }
}
