import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Param,
  Body,
  Query,
  UseGuards,
  HttpCode,
  HttpStatus,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
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 } from '../../../common/decorators/current-user.decorator';
import { TrainingManager } from '../entities/training/training.manager';
import { CreateCrmTrainingDto } from '../dto/create-training.dto';
import { UpdateCrmTrainingDto } from '../dto/update-training.dto';

@ApiTags('CRM Trainings')
@ApiBearerAuth()
@Controller('crm/trainings')
@UseGuards(JwtAuthGuard)
export class TrainingsController {
  constructor(private readonly trainingManager: TrainingManager) {}

  @Get()
  @ApiOperation({ summary: 'List trainings' })
  @ApiQuery({ name: 'dealId', required: false })
  @ApiQuery({ name: 'cursor', required: false })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  @ApiResponse({ status: 200 })
  async findAll(
    @CurrentUser() user: any,
    @Query('dealId') dealId?: string,
    @Query('cursor') cursor?: string,
    @Query('limit') limit?: string,
  ) {
    const where: Record<string, any> = {};
    if (dealId) where.dealId = dealId;
    if (user.role !== UserRole.SUPER_ADMIN) where.clubId = user.clubId;

    return this.trainingManager.getList(where, {
      cursor,
      limit: limit ? +limit : undefined,
    });
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get training by ID' })
  @ApiResponse({ status: 200 })
  async findById(@Param('id', ParseUUIDPipe) id: string) {
    return this.trainingManager.getById(id);
  }

  @Post()
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN, UserRole.MANAGER)
  @ApiOperation({ summary: 'Create a training' })
  @ApiResponse({ status: 201 })
  async create(@CurrentUser() user: any, @Body() dto: CreateCrmTrainingDto) {
    const clubId = user.role === UserRole.SUPER_ADMIN ? null : user.clubId;
    return this.trainingManager.add(
      {
        ...dto,
        clubId,
        scheduledAt: new Date(dto.scheduledAt),
      } as any,
      { userId: user.sub },
    );
  }

  @Patch(':id')
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN, UserRole.MANAGER)
  @ApiOperation({ summary: 'Update a training' })
  async update(
    @Param('id', ParseUUIDPipe) id: string,
    @CurrentUser() user: any,
    @Body() dto: UpdateCrmTrainingDto,
  ) {
    const data: Record<string, any> = { ...dto };
    if (dto.scheduledAt) data.scheduledAt = new Date(dto.scheduledAt);
    return this.trainingManager.update(id, data, { userId: user.sub });
  }

  @Delete(':id')
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN)
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Delete a training' })
  async remove(@Param('id', ParseUUIDPipe) id: string, @CurrentUser() user: any) {
    await this.trainingManager.delete(id, { userId: user.sub });
  }
}
