import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';

import { TrainSchedulingManage, TrainSchedulingView } from '../../common/booking-guards';

import { CreateLastMileDto } from './dto/create-last-mile.dto';
import { UpdateLastMileDto } from './dto/update-last-mile.dto';
import { LastMileStatus } from './entities/last-mile.entity';
import { LastMileService } from './last-mile.service';

@ApiTags('last-mile')
@ApiBearerAuth()
@Controller('last-mile')
@TrainSchedulingView()
export class LastMileController {
  constructor(private readonly lastMileService: LastMileService) {}

  @Get()
  @ApiOperation({ summary: 'List last-mile legs' })
  findAll(
    @Query('status') status?: string,
    @Query('bookingId') bookingId?: string,
    @Query('vehicleId') vehicleId?: string,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('sortBy') sortBy?: string,
    @Query('sortOrder') sortOrder?: 'ASC' | 'DESC',
  ) {
    return this.lastMileService.findAll({
      status: status as LastMileStatus | undefined,
      bookingId,
      vehicleId,
      page: page ? parseInt(page, 10) : undefined,
      pageSize: pageSize ? parseInt(pageSize, 10) : undefined,
      sortBy,
      sortOrder,
    });
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get a last-mile leg by ID' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.lastMileService.findById(id);
  }

  @Post('accept/:reference')
  @TrainSchedulingManage()
  @ApiOperation({ summary: 'Accept a paid booking and create a last-mile leg' })
  acceptBooking(@Param('reference') reference: string) {
    return this.lastMileService.acceptBooking(reference);
  }

  @Post()
  @TrainSchedulingManage()
  @ApiOperation({ summary: 'Create a last-mile leg' })
  create(@Body() dto: CreateLastMileDto) {
    return this.lastMileService.create(dto);
  }

  @Patch(':id')
  @TrainSchedulingManage()
  @ApiOperation({ summary: 'Update a last-mile leg' })
  update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateLastMileDto) {
    return this.lastMileService.update(id, dto);
  }

  @Delete(':id')
  @TrainSchedulingManage()
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Soft-delete a last-mile leg' })
  remove(@Param('id', ParseUUIDPipe) id: string) {
    return this.lastMileService.remove(id);
  }
}
