import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Param,
  Body,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { LocationsService } from './locations.service';
import { Locations } from './entities/locations.entity';
import {
  ApiBearerAuth,
  ApiTags,
  ApiOperation,
  ApiBody,
  ApiParam,
} from '@nestjs/swagger';

@ApiTags('locations')
@ApiBearerAuth('access-token')
@Controller('locations')
export class LocationsController {
  constructor(private readonly locationsService: LocationsService) {}

  @Get()
  @ApiOperation({ summary: 'Get all locations' })
  async findAll(): Promise<Locations[]> {
    try {
      return await this.locationsService.findAll();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch locations',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get location by id' })
  @ApiParam({ name: 'id', type: Number })
  async findOne(@Param('id') id: number): Promise<Locations> {
    try {
      return await this.locationsService.findOne(+id);
    } catch (error) {
      throw new HttpException(
        error.message,
        error.status || HttpStatus.NOT_FOUND,
      );
    }
  }

  @Post()
  @ApiOperation({ summary: 'Create location' })
  @ApiBody({ type: Locations })
  async create(@Body() data: Partial<Locations>): Promise<Locations> {
    try {
      return await this.locationsService.create(data);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }

  @Put(':id')
  @ApiOperation({ summary: 'Update location' })
  @ApiParam({ name: 'id', type: Number })
  @ApiBody({ type: Locations })
  async update(
    @Param('id') id: number,
    @Body() data: Partial<Locations>,
  ): Promise<Locations> {
    try {
      return await this.locationsService.update(+id, data);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete location' })
  @ApiParam({ name: 'id', type: Number })
  async remove(@Param('id') id: number): Promise<{ message: string }> {
    try {
      return await this.locationsService.remove(+id);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }
}
