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

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

import { SessionGuard } from '../auth/guards/session.guard';
import { PrismaService } from '../prisma/prisma.service';

import { CatalogService } from './catalog.service';

@ApiTags('catalog')
@Controller('catalog')
@UseGuards(SessionGuard)
export class CatalogController {
  constructor(
    private readonly catalogService: CatalogService,
    private readonly prisma: PrismaService,
  ) {}

  @Get('projects')
  @ApiOperation({ summary: 'Search Modrinth projects' })
  search(@Query() query: Record<string, string | undefined>) {
    const input = catalogSearchQuerySchema.parse({
      q: query['q'],
      gameVersion: query['gameVersion'],
      softwareFamily: query['softwareFamily'],
      limit: query['limit'],
    });

    return this.catalogService.searchProjects({
      query: input.q,
      gameVersion: input.gameVersion,
      softwareFamily: input.softwareFamily,
      limit: input.limit,
    });
  }

  @Get('projects/:projectId/versions')
  @ApiOperation({ summary: 'List Modrinth project versions' })
  async versions(
    @Param('projectId') projectId: string,
    @Query('serverId') serverId?: string,
    @Query('gameVersion') gameVersion?: string,
    @Query('softwareFamily') softwareFamily?: string,
  ) {
    let resolvedGameVersion = gameVersion;
    let resolvedSoftwareFamily = softwareFamily;

    if (serverId) {
      const server = await this.prisma.gameServer.findUniqueOrThrow({
        where: { id: serverId },
      });
      resolvedGameVersion = server.minecraftVersion;
      resolvedSoftwareFamily = server.softwareFamily;
    }

    if (!resolvedGameVersion || !resolvedSoftwareFamily) {
      throw new BadRequestException('gameVersion and softwareFamily are required');
    }

    return this.catalogService.listProjectVersions(
      projectId,
      resolvedGameVersion,
      resolvedSoftwareFamily as 'PAPER' | 'FABRIC' | 'PURPUR' | 'FORGE' | 'NEOFORGE' | 'QUILT',
    );
  }
}
