import { Body, Controller, Param, ParseUUIDPipe, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '@edr/api-common';

import { TrainSchedulingManage } from '../../common/booking-guards';
import {
  type AuthUserPayload,
  resolveAuthUserId,
} from '../../common/resolve-auth-user-id';
import { ExecuteRescheduleDto, PreviewRescheduleDto } from './dto/preview-reschedule.dto';
import { SchedulingRescheduleService } from './scheduling-reschedule.service';

@ApiTags('train-scheduling')
@ApiBearerAuth()
@Controller('train-scheduling/schedules/:id/reschedule')
export class SchedulingRescheduleController {
  constructor(private readonly schedulingRescheduleService: SchedulingRescheduleService) {}

  @Post('preview')
  @TrainSchedulingManage()
  @ApiOperation({ summary: 'Preview reschedule / government preempt plan' })
  preview(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: PreviewRescheduleDto,
  ) {
    return this.schedulingRescheduleService.previewReschedule(id, dto);
  }

  @Post('execute')
  @TrainSchedulingManage()
  @ApiOperation({ summary: 'Execute a confirmed reschedule plan' })
  execute(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: ExecuteRescheduleDto,
    @CurrentUser() user: AuthUserPayload,
  ) {
    return this.schedulingRescheduleService.executeReschedule(
      id,
      dto,
      resolveAuthUserId(user),
    );
  }
}

@ApiTags('train-scheduling')
@ApiBearerAuth()
@Controller('train-scheduling/schedules/:id')
export class SchedulingMaintenanceController {
  constructor(private readonly schedulingRescheduleService: SchedulingRescheduleService) {}

  @Post('maintenance')
  @TrainSchedulingManage()
  @ApiOperation({ summary: 'Reschedule train for maintenance (new departure + rebalance)' })
  maintenance(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: PreviewRescheduleDto & { newDepartureDate: string },
    @CurrentUser() user: AuthUserPayload,
  ) {
    return this.schedulingRescheduleService.maintenanceReschedule(
      id,
      dto,
      resolveAuthUserId(user),
    );
  }
}
