import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Request,
  Patch,
} from '@nestjs/common';
import { InviteCodesService } from './invite-codes.service';
import { CreateInviteCodeDto, UpdateInviteCodeDto } from './invite-codes.dto';
import { AdminGuard } from '../../common/guards/admin.guard';

@Controller('api/v1/admin/invite-codes')
@UseGuards(AdminGuard)
export class InviteCodesController {
  constructor(private readonly inviteCodesService: InviteCodesService) {}

  @Post()
  async create(@Body() dto: CreateInviteCodeDto, @Request() req: any) {
    // For now, we'll pass undefined for createdBy until we implement admin auth
    return this.inviteCodesService.create(dto, req.user?.id);
  }

  @Get()
  async findAll(
    @Query('page') page?: string,
    @Query('limit') limit?: string,
    @Query('status') status?: string,
  ) {
    return this.inviteCodesService.findAll({
      page: page ? parseInt(page, 10) : undefined,
      limit: limit ? parseInt(limit, 10) : undefined,
      status,
    });
  }

  @Get('generate')
  async generateCode() {
    const code = await this.inviteCodesService.generateRandomCode();
    return { code };
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    return this.inviteCodesService.findOne(id);
  }

  @Get(':id/stats')
  async getStats(@Param('id') id: string) {
    return this.inviteCodesService.getUsageStats(id);
  }

  @Put(':id')
  async update(@Param('id') id: string, @Body() dto: UpdateInviteCodeDto) {
    return this.inviteCodesService.update(id, dto);
  }

  @Patch(':id')
  async patch(@Param('id') id: string, @Body() dto: UpdateInviteCodeDto) {
    return this.inviteCodesService.update(id, dto);
  }

  @Delete(':id')
  async remove(@Param('id') id: string) {
    await this.inviteCodesService.delete(id);
    return { message: 'Invite code deleted successfully' };
  }
}

// Public controller for validating invite codes during registration
@Controller('api/v1/invite-codes')
export class PublicInviteCodesController {
  constructor(private readonly inviteCodesService: InviteCodesService) {}

  @Post('validate')
  async validate(@Body('code') code: string) {
    const result = await this.inviteCodesService.validateCode(code);
    return {
      isValid: result.isValid,
      reason: result.reason,
    };
  }
}