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

import type { AddonListResponse, InstallAddonResponse } from '@hexahost/contracts';
import { installAddonRequestSchema } from '@hexahost/contracts';

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

import { AddonsService } from './addons.service';

@ApiTags('servers')
@Controller('servers/:serverId/addons')
@UseGuards(SessionGuard)
export class AddonsController {
  constructor(private readonly addonsService: AddonsService) {}

  @Get()
  @ApiOperation({ summary: 'List installed add-ons' })
  list(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
  ): Promise<AddonListResponse> {
    return this.addonsService.listAddons(user.id, serverId);
  }

  @Post()
  @ApiOperation({ summary: 'Install an add-on from the catalog' })
  install(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
    @Body() body: unknown,
  ) {
    const input = installAddonRequestSchema.parse(body);
    return this.addonsService.installAddon(user.id, serverId, input);
  }

  @Delete(':addonId')
  @ApiOperation({ summary: 'Remove an installed add-on' })
  remove(
    @CurrentUser() user: { id: string },
    @Param('serverId', ParseUUIDPipe) serverId: string,
    @Param('addonId', ParseUUIDPipe) addonId: string,
  ): Promise<InstallAddonResponse> {
    return this.addonsService.removeAddon(user.id, serverId, addonId);
  }
}
