import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  Body,
  UseGuards,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import {
  ApiTags,
  ApiBearerAuth,
  ApiOperation,
  ApiProperty,
  ApiPropertyOptional,
} from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsOptional, IsUUID, IsDateString } from 'class-validator';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles, UserRole } from '../../../common/decorators/roles.decorator';
import { CurrentUser, JwtPayload } from '../../../common/decorators/current-user.decorator';
import { RequireModule } from '../../../common/decorators/require-module.decorator';
import { ModuleGuard } from '../../../common/guards/module.guard';
import { WaitlistService } from '../services/waitlist.service';

class AddToWaitlistBodyDto {
  @ApiProperty() @IsString() @IsNotEmpty() clientName: string;
  @ApiProperty() @IsString() @IsNotEmpty() clientPhone: string;
  @ApiProperty() @IsUUID() serviceId: string;
  @ApiPropertyOptional() @IsUUID() @IsOptional() staffId?: string;
  @ApiPropertyOptional() @IsDateString() @IsOptional() preferredDate?: string;
  @ApiPropertyOptional() @IsString() @IsOptional() preferredTime?: string;
  @ApiPropertyOptional() @IsString() @IsOptional() notes?: string;
}

class ConvertWaitlistDto {
  @ApiProperty() @IsUUID() staffId: string;
  @ApiProperty() @IsDateString() startAt: string;
}

@ApiTags('Booking / Waitlist')
@ApiBearerAuth()
@Controller('booking/waitlist')
@UseGuards(JwtAuthGuard, ModuleGuard)
@RequireModule('booking')
export class BookingWaitlistController {
  constructor(private readonly waitlistService: WaitlistService) {}

  @Get()
  @ApiOperation({ summary: 'List waitlist entries' })
  async findAll(@CurrentUser() user: JwtPayload) {
    return this.waitlistService.findAll(user.clubId);
  }

  @Post()
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN, UserRole.MANAGER, UserRole.RECEPTIONIST)
  @ApiOperation({ summary: 'Add to waitlist' })
  async add(@CurrentUser() user: JwtPayload, @Body() dto: AddToWaitlistBodyDto) {
    return this.waitlistService.add(user.clubId, dto);
  }

  @Post(':id/convert')
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN, UserRole.MANAGER)
  @ApiOperation({ summary: 'Convert waitlist entry to booking record' })
  async convert(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: ConvertWaitlistDto,
  ) {
    return this.waitlistService.convertToRecord(id, dto, user.sub);
  }

  @Delete(':id')
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN, UserRole.MANAGER)
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Remove from waitlist' })
  async delete(@Param('id', ParseUUIDPipe) id: string) {
    await this.waitlistService.delete(id);
  }
}
