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

import { CurrentUser } from '../../auth/decorators/current-user.decorator';
import { SessionGuard } from '../../auth/guards/session.guard';
import { PrismaService } from '../../prisma/prisma.service';
import { findOwnedServer } from '../shared/server-ownership.util';

import { ConsoleService } from './console.service';

@ApiTags('servers')
@Controller('servers/:serverId/console')
@UseGuards(SessionGuard)
export class ConsoleController {
  constructor(
    private readonly consoleService: ConsoleService,
    private readonly prisma: PrismaService,
  ) {}

  @Get('token')
  @ApiOperation({ summary: 'Issue a short-lived console WebSocket token' })
  @ApiResponse({ status: 200, description: 'Console token issued' })
  async issueToken(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
  ) {
    await findOwnedServer(this.prisma, user.id, serverId);
    return this.consoleService.issueToken(serverId, user.id);
  }
}
