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

import { createServerRequestSchema } from '@hexahost/contracts';

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

import { ServersService } from './servers.service';

@ApiTags('servers')
@Controller('servers')
@UseGuards(SessionGuard)
export class ServersController {
  constructor(private readonly serversService: ServersService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Create a game server' })
  @ApiResponse({ status: 201, description: 'Server created' })
  create(
    @CurrentUser() user: { id: string },
    @Body(new ZodValidationPipe(createServerRequestSchema)) body: unknown,
  ) {
    return this.serversService.createServer(
      user.id,
      body as Parameters<ServersService['createServer']>[1],
    );
  }

  @Get()
  @ApiOperation({ summary: 'List owned game servers' })
  list(@CurrentUser() user: { id: string }) {
    return this.serversService.listServers(user.id);
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get a game server by id' })
  get(
    @CurrentUser() user: { id: string },
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    return this.serversService.getServer(user.id, id);
  }

  @Post(':id/start')
  @HttpCode(HttpStatus.ACCEPTED)
  @ApiOperation({ summary: 'Start a game server' })
  start(
    @CurrentUser() user: { id: string },
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    return this.serversService.startServer(user.id, id);
  }

  @Post(':id/stop')
  @HttpCode(HttpStatus.ACCEPTED)
  @ApiOperation({ summary: 'Stop a game server' })
  stop(
    @CurrentUser() user: { id: string },
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    return this.serversService.stopServer(user.id, id);
  }
}
