import {
  Body,
  Controller,
  HttpCode,
  HttpStatus,
  Post,
  UseGuards,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { z } from 'zod';

import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { SessionGuard } from '../auth/guards/session.guard';
import { ZodValidationPipe } from '../common/pipes/zod-validation.pipe';

import { AdminNodesService } from './admin-nodes.service';
import type { CreateNodeResponse } from './admin-nodes.service';

const createNodeRequestSchema = z.object({
  name: z.string().min(1).max(64),
  hostname: z.string().min(1).max(255),
  maxServers: z.number().int().min(1).max(1000).optional(),
});

@ApiTags('admin')
@Controller('admin/nodes')
@UseGuards(SessionGuard)
export class AdminNodesController {
  constructor(private readonly adminNodesService: AdminNodesService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Register a new game node (super admin only)' })
  @ApiResponse({ status: 201, description: 'Node created with enrollment token' })
  create(
    @CurrentUser() user: { roles: string[] },
    @Body(new ZodValidationPipe(createNodeRequestSchema)) body: unknown,
  ): Promise<CreateNodeResponse> {
    this.adminNodesService.assertSuperAdmin(user.roles);

    return this.adminNodesService.createNode(
      body as Parameters<AdminNodesService['createNode']>[0],
    );
  }
}
