import { BadRequestException, Injectable } from '@nestjs/common';

import type {
  CatalogSearchResponse,
  CatalogVersionsResponse,
} from '@hexahost/contracts';
import {
  getModrinthProjectVersions,
  isVersionCompatible,
  resolveModrinthLoader,
  resolveProjectType,
  searchModrinthProjects,
  type SoftwareFamily,
} from '@hexahost/catalog';

@Injectable()
export class CatalogService {
  async searchProjects(input: {
    query: string;
    gameVersion: string;
    softwareFamily: SoftwareFamily;
    limit?: number;
  }): Promise<CatalogSearchResponse> {
    const projectType = resolveProjectType(input.softwareFamily);
    const loader = resolveModrinthLoader(input.softwareFamily);

    if (!projectType || !loader) {
      throw new BadRequestException(
        'This server software does not support catalog add-ons',
      );
    }

    const result = await searchModrinthProjects({
      query: input.query,
      projectType,
      gameVersion: input.gameVersion,
      loader,
      limit: input.limit,
    });

    return {
      projects: result.hits.map((project) => ({
        id: project.project_id,
        slug: project.slug,
        name: project.title,
        description: project.description,
        projectType: project.project_type,
        downloads: project.downloads,
        iconUrl: project.icon_url ?? null,
      })),
    };
  }

  async listProjectVersions(
    projectId: string,
    gameVersion: string,
    softwareFamily: SoftwareFamily,
  ): Promise<CatalogVersionsResponse> {
    const loader = resolveModrinthLoader(softwareFamily);
    if (!loader) {
      throw new BadRequestException(
        'This server software does not support catalog add-ons',
      );
    }

    const versions = await getModrinthProjectVersions(projectId);

    return {
      versions: versions.map((version) => ({
        id: version.id,
        projectId: version.project_id,
        name: version.name,
        versionNumber: version.version_number,
        gameVersions: version.game_versions,
        loaders: version.loaders,
        compatible: isVersionCompatible(version, gameVersion, loader),
        publishedAt: version.date_published,
      })),
    };
  }
}
