import { apiFetch } from "./auth";
import type { SoftwareFamily } from "./servers";

export interface CatalogProject {
  id: string;
  slug: string;
  name: string;
  description: string;
  projectType: string;
  downloads: number;
  iconUrl: string | null;
}

export interface CatalogVersion {
  id: string;
  projectId: string;
  name: string;
  versionNumber: string;
  gameVersions: string[];
  loaders: string[];
  compatible: boolean;
  publishedAt: string;
}

export interface InstalledAddon {
  id: string;
  projectId: string;
  projectName: string;
  versionNumber: string;
  addonType: string;
  fileName: string;
  status: string;
  failureReason: string | null;
}

export async function searchCatalog(input: {
  q: string;
  gameVersion: string;
  softwareFamily: SoftwareFamily;
}): Promise<{ projects: CatalogProject[] }> {
  const params = new URLSearchParams({
    q: input.q,
    gameVersion: input.gameVersion,
    softwareFamily: input.softwareFamily,
  });
  return apiFetch(`/catalog/projects?${params.toString()}`);
}

export async function listCatalogVersions(
  projectId: string,
  serverId: string,
): Promise<{ versions: CatalogVersion[] }> {
  const params = new URLSearchParams({ serverId });
  return apiFetch(`/catalog/projects/${projectId}/versions?${params.toString()}`);
}

export async function listInstalledAddons(
  serverId: string,
): Promise<{ addons: InstalledAddon[] }> {
  return apiFetch(`/servers/${serverId}/addons`);
}

export async function installAddon(
  serverId: string,
  projectId: string,
  versionId: string,
): Promise<unknown> {
  return apiFetch(`/servers/${serverId}/addons`, {
    method: "POST",
    body: JSON.stringify({ projectId, versionId }),
  });
}

export async function removeAddon(
  serverId: string,
  addonId: string,
): Promise<unknown> {
  return apiFetch(`/servers/${serverId}/addons/${addonId}`, {
    method: "DELETE",
  });
}
