import { Controller, Post, Get, Body, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { EnhancedSeatsService } from './enhanced-seats.service';
import { ConfirmBookingDto, SeatAvailabilityDto, ReleaseSeatsDto } from './segments.dto';

@ApiTags('Segment-based Seats')
@Controller('segments/seats')
export class SegmentSeatsController {
  constructor(private enhancedSeatsService: EnhancedSeatsService) {}

  @Post('confirm')
  @ApiOperation({
    summary: 'Confirm booking — convert hold to reservation',
    description: 'Call after payment succeeds. Converts the SeatHold (created via POST /seats/hold) into JourneySegment records scoped to the passenger\'s leg.',
  })
  @ApiResponse({ status: 200, description: 'Booking confirmed, JourneySegments created for the held leg' })
  @ApiResponse({ status: 400, description: 'Hold expired or booking not found' })
  confirmBooking(@Body() dto: ConfirmBookingDto) {
    return this.enhancedSeatsService.confirmBooking(dto);
  }

  @Post('release')
  @ApiOperation({
    summary: 'Release seats when train reaches a station',
    description: 'Called by the live tracking system when the train departs a station. Frees seats for passengers whose journey ended at that station.',
  })
  @ApiResponse({ status: 200, description: 'Seats released for passengers who reached their destination' })
  releaseSeats(@Body() dto: ReleaseSeatsDto) {
    return this.enhancedSeatsService.releaseSeats(dto.scheduleId, dto.currentStationId);
  }

  @Get('availability')
  @ApiOperation({
    summary: 'Get available seats for a specific leg',
    description: 'Returns seats that have no overlapping reservation for the requested origin→destination leg. A seat booked A→B is shown as available for B→D.',
  })
  @ApiResponse({ status: 200, description: 'Available seats with coach, seat class, row, col, window/aisle/bed flags' })
  getSeatAvailability(@Query() dto: SeatAvailabilityDto) {
    return this.enhancedSeatsService.getSeatAvailability(dto.scheduleId, dto.originStationId, dto.destinationStationId);
  }

  @Post('expire-holds')
  @ApiOperation({
    summary: 'Expire stale seat holds (background job)',
    description: 'Removes holds past their expiry time. Called by the scheduler every minute.',
  })
  @ApiResponse({ status: 200, description: 'Expired holds removed' })
  expireHolds() {
    return this.enhancedSeatsService.expireHolds();
  }
}