import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Request, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AgentsService } from './agents.service';
import { CreateAgentDto, CreateAgentBookingDto, OpenShiftDto, CloseShiftDto } from './agents.dto';
import { JwtGuard as IamJwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard';
import { PassengerAdmin } from '../../common/passenger-guards';

@ApiTags('Agents')
@Controller('agents')
@UseGuards(IamJwtGuard)
@ApiBearerAuth('IAM-auth')
export class AgentsController {
  constructor(private service: AgentsService) {}

  @Get('me')
  @ApiOperation({ summary: 'Get agent profile for logged-in IAM user' })
  getMe(@Request() req: any) {
    return this.service.getMe(req.user?.id ?? req.user?.sub);
  }

  @Get()
  @ApiOperation({ summary: 'List all agents' })
  findAll(@Query('search') search?: string, @Query('active') active?: string) {
    return this.service.findAll({ search, active });
  }

  @Post()
  @ApiOperation({ summary: 'Create agent profile linked to an IAM user' })
  createAgent(@Body() dto: CreateAgentDto) {
    return this.service.createAgent(dto);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Update agent profile' })
  updateAgent(@Param('id') id: string, @Body() dto: Partial<CreateAgentDto> & { active?: boolean }) {
    return this.service.updateAgent(id, dto);
  }

  @Delete(':id')
  @PassengerAdmin()
  @ApiBearerAuth('IAM-auth')
  @ApiOperation({ summary: 'Delete agent profile' })
  deleteAgent(@Param('id') id: string) {
    return this.service.deleteAgent(id);
  }
  @Post('bookings')
  @ApiOperation({ summary: 'Create agent booking with cash payment' })
  createBooking(@Body() dto: CreateAgentBookingDto) {
    return this.service.createAgentBooking(dto);
  }

  @Post('shifts/open')
  @ApiOperation({ summary: 'Open agent shift' })
  openShift(@Body() dto: OpenShiftDto) {
    return this.service.openShift(dto);
  }

  @Post('shifts/close')
  @ApiOperation({ summary: 'Close agent shift' })
  closeShift(@Body() dto: CloseShiftDto) {
    return this.service.closeShift(dto);
  }

  @Get(':agentId/commissions')
  @ApiOperation({ summary: 'Get agent commissions' })
  getCommissions(
    @Param('agentId') agentId: string,
    @Query('dateFrom') dateFrom?: string,
    @Query('dateTo') dateTo?: string
  ) {
    return this.service.getCommissions(
      agentId,
      dateFrom ? new Date(dateFrom) : undefined,
      dateTo ? new Date(dateTo) : undefined
    );
  }

  @Get(':agentId/shifts')
  @ApiOperation({ summary: 'Get agent shifts' })
  getShifts(@Param('agentId') agentId: string) {
    return this.service.getShifts(agentId);
  }
}
