import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Param,
  Body,
  Query,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { BookingStaff } from '../../common/booking-guards';
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
import { VehiclesService } from './vehicles.service';
import { CreateVehicleDto } from './dto/create-vehicle.dto';
import { UpdateVehicleDto } from './dto/update-vehicle.dto';
import { FleetHistoryService } from '../fleet-history/fleet-history.service';

@ApiTags('vehicles')
@ApiBearerAuth()
@Controller('vehicles')
@BookingStaff(FREIGHT_PERMS.vehicles.view)
export class VehiclesController {
  constructor(
    private readonly vehiclesService: VehiclesService,
    private readonly fleetHistory: FleetHistoryService,
  ) {}

  @Post()
  @BookingStaff(FREIGHT_PERMS.vehicles.create)
  @ApiOperation({ summary: 'Create a new vehicle' })
  create(@Body() createVehicleDto: CreateVehicleDto) {
    return this.vehiclesService.create(createVehicleDto);
  }

  @Get()
  @ApiOperation({ summary: 'Get all vehicles with filters' })
  findAll(
    @Query('search') search?: string,
    @Query('status') status?: string,
    @Query('availability') availability?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
    @Query('sortBy') sortBy?: string,
    @Query('sortOrder') sortOrder?: 'ASC' | 'DESC',
  ) {
    return this.vehiclesService.findAll({
      search,
      status: status as any,
      availability: availability as any,
      page: page ? parseInt(page) : undefined,
      limit: limit ? parseInt(limit) : undefined,
      sortBy,
      sortOrder,
    });
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get vehicle by id' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.vehiclesService.findById(id);
  }

  @Get(':id/history')
  @ApiOperation({ summary: 'Get vehicle assignment, status & mile history' })
  history(@Param('id', ParseUUIDPipe) id: string) {
    return this.fleetHistory.getVehicleHistory(id);
  }

  @Patch(':id')
  @BookingStaff(FREIGHT_PERMS.vehicles.update)
  @ApiOperation({ summary: 'Update a vehicle' })
  update(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() updateVehicleDto: UpdateVehicleDto,
  ) {
    return this.vehiclesService.update(id, updateVehicleDto);
  }

  @Delete(':id')
  @BookingStaff(FREIGHT_PERMS.vehicles.delete)
  @ApiOperation({ summary: 'Delete a vehicle' })
  remove(@Param('id', ParseUUIDPipe) id: string) {
    return this.vehiclesService.remove(id);
  }
}
