import { BadRequestException, Body, Controller, Get, Param, ParseIntPipe, Post, Query } from '@nestjs/common';
import {
  searchLocationsQuerySchema,
  createLocationFromPlaceSchema,
  type CreateLocationFromPlaceInput,
  type AuthUser,
} from '@vihar/shared';
import { LocationsService } from './locations.service';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { CurrentUser, RequiresCaptain } from '../../common/decorators/auth.decorators';

@Controller('locations')
export class LocationsController {
  constructor(private readonly locations: LocationsService) {}

  @Get()
  search(
    @CurrentUser() user: AuthUser,
    @Query(new ZodValidationPipe(searchLocationsQuerySchema)) q: ReturnType<typeof searchLocationsQuerySchema.parse>,
  ) {
    if (!user.cityId) throw new BadRequestException('No city scope');
    return this.locations.search(user.cityId, q);
  }

  @Get(':id')
  get(@CurrentUser() user: AuthUser, @Param('id', ParseIntPipe) id: number) {
    if (!user.cityId) throw new BadRequestException('No city scope');
    return this.locations.getById(user.cityId, id);
  }

  @Post('from-place-id')
  @RequiresCaptain()
  createFromPlaceId(
    @CurrentUser() user: AuthUser,
    @Body(new ZodValidationPipe(createLocationFromPlaceSchema)) input: CreateLocationFromPlaceInput,
  ) {
    if (!user.cityId) throw new BadRequestException('No city scope');
    return this.locations.createFromPlaceId(user.cityId, user.userId, input);
  }
}
