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

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

import { CurrentUser } from '../../auth/decorators/current-user.decorator';
import { SessionGuard } from '../../auth/guards/session.guard';

import { WorldsService } from './worlds.service';

@ApiTags('servers')
@Controller('servers/:serverId/worlds')
@UseGuards(SessionGuard)
export class WorldsController {
  constructor(private readonly worldsService: WorldsService) {}

  @Get()
  @ApiOperation({ summary: 'Get world overview' })
  info(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
  ) {
    return this.worldsService.getWorldInfo(user.id, serverId);
  }

  @Post('uploads')
  @ApiOperation({ summary: 'Initiate a world upload' })
  initiateUpload(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
    @Body() body: unknown,
  ) {
    const input = initiateWorldUploadSchema.parse(body);
    return this.worldsService.initiateUpload(user.id, serverId, input);
  }

  @Post('uploads/:uploadId/complete')
  @ApiOperation({ summary: 'Complete a world upload and apply it' })
  completeUpload(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
    @Param('uploadId', ParseUUIDPipe) uploadId: string,
  ) {
    return this.worldsService.completeUpload(user.id, serverId, uploadId);
  }

  @Post('download')
  @ApiOperation({ summary: 'Create a backup for world download' })
  download(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
  ) {
    return this.worldsService.requestWorldDownload(user.id, serverId);
  }
}
