import {
  Controller,
  Get,
  Patch,
  Param,
  Body,
  UseGuards,
  NotFoundException,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiResponse,
  ApiParam,
} from '@nestjs/swagger';
import { ModulesService, ClubModule } from './modules.service';
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';

@ApiTags('Modules')
@ApiBearerAuth()
@Controller('modules')
@UseGuards(JwtAuthGuard)
export class ModulesController {
  constructor(private readonly modulesService: ModulesService) {}

  @Get()
  @ApiOperation({ summary: 'List all modules for the current club' })
  @ApiResponse({ status: 200, description: 'List of club modules' })
  async getAllModules(@CurrentUser() user: JwtPayload): Promise<ClubModule[]> {
    return this.modulesService.getAllModules(user.clubId);
  }

  @Get(':moduleId')
  @ApiOperation({ summary: 'Get a specific module for the current club' })
  @ApiParam({ name: 'moduleId', description: 'Module identifier (e.g. sip, webhooks)' })
  @ApiResponse({ status: 200, description: 'Club module details' })
  @ApiResponse({ status: 404, description: 'Module not found' })
  async getModule(
    @CurrentUser() user: JwtPayload,
    @Param('moduleId') moduleId: string,
  ): Promise<ClubModule> {
    const mod = await this.modulesService.getModule(user.clubId, moduleId);

    if (!mod) {
      throw new NotFoundException(
        `Module "${moduleId}" not found for this club`,
      );
    }

    return mod;
  }

  @Patch(':moduleId/enable')
  @UseGuards(RolesGuard)
  @Roles(UserRole.CLUB_ADMIN)
  @ApiOperation({ summary: 'Enable a module for the current club' })
  @ApiParam({ name: 'moduleId', description: 'Module identifier' })
  @ApiResponse({ status: 200, description: 'Module enabled' })
  @ApiResponse({ status: 403, description: 'Insufficient role' })
  async enableModule(
    @CurrentUser() user: JwtPayload,
    @Param('moduleId') moduleId: string,
    @Body() body: { limits?: Record<string, unknown> },
  ): Promise<ClubModule> {
    return this.modulesService.enableModule(
      user.clubId,
      moduleId,
      body?.limits,
    );
  }

  @Patch(':moduleId/disable')
  @UseGuards(RolesGuard)
  @Roles(UserRole.CLUB_ADMIN)
  @ApiOperation({ summary: 'Disable a module for the current club' })
  @ApiParam({ name: 'moduleId', description: 'Module identifier' })
  @ApiResponse({ status: 200, description: 'Module disabled' })
  @ApiResponse({ status: 403, description: 'Insufficient role' })
  @ApiResponse({ status: 404, description: 'Module not found' })
  async disableModule(
    @CurrentUser() user: JwtPayload,
    @Param('moduleId') moduleId: string,
  ): Promise<ClubModule> {
    return this.modulesService.disableModule(user.clubId, moduleId);
  }
}
