import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { CreateWagonDto } from './dto/create-wagon.dto';
import { UpdateWagonDto } from './dto/update-wagon.dto';
import { AssignWagonToTrainDto } from './dto/assign-wagon-to-train.dto';
import { ReorderWagonsDto } from './dto/reorder-wagons.dto';
import { WagonsService } from './wagons.service';

@ApiTags('wagons')
@Controller('wagons')
export class WagonsController {
  constructor(private readonly wagonsService: WagonsService) {}

  @Post()
  @ApiOperation({ summary: 'Create a new wagon' })
  create(@Body() dto: CreateWagonDto) {
    return this.wagonsService.create(dto);
  }

  @Get()
  @ApiOperation({ summary: 'List all wagons' })
  findAll(@Query() query: Record<string, string | undefined>) {
    return this.wagonsService.findAll(query);
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get a wagon by ID' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.wagonsService.findById(id);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Update a wagon' })
  update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateWagonDto) {
    return this.wagonsService.update(id, dto);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete a wagon' })
  remove(@Param('id', ParseUUIDPipe) id: string) {
    return this.wagonsService.remove(id);
  }

  @Post(':id/assign-train')
  @ApiOperation({ summary: 'Assign wagon to a train' })
  assignToTrain(@Param('id', ParseUUIDPipe) id: string, @Body() dto: AssignWagonToTrainDto) {
    return this.wagonsService.assignToTrain(id, dto);
  }

  @Post(':id/unassign-train')
  @ApiOperation({ summary: 'Unassign wagon from train' })
  unassignFromTrain(@Param('id', ParseUUIDPipe) id: string) {
    return this.wagonsService.unassignFromTrain(id);
  }
}

// Separate controller for train‑specific reorder (registered in module)
@Controller('trains/:trainId/reorder-wagons')
export class TrainWagonsReorderController {
  constructor(private readonly wagonsService: WagonsService) {}

  @Post()
  @ApiOperation({ summary: 'Reorder wagons of a train' })
  reorder(@Param('trainId', ParseUUIDPipe) trainId: string, @Body() dto: ReorderWagonsDto) {
    return this.wagonsService.reorderWagons(trainId, dto);
  }
}
