import { Loader } from "../types/mcgrizzconf.ts";

export type ModrinthProjectSearchResult = {
  project_id: string;
  project_type: string;
  slug: string;
  author: string;
  title: string;
  description: string;
  categories: string[];
  display_categories: string[];
  versions: string[];
  downloads: number;
  follows: number;
  icon_url: string;
  date_created: string;
  date_modified: string;
  latest_version: string;
  license: string;
  client_side: string;
  server_side: string;
  gallery: string[];
  featured_gallery: string;
  color: number;
};

export type ModrinthProject = {
  id: string;
  slug: string;
  project_type: string;
  team: string;
  title: string;
  description: string;
  // Markdown
  body: string;
  body_url: string | null;
  published: string;
  updated: string;
  approved: string;
  queued: string;
  status: string;
  requested_status: string;
  moderator_message: string | null;
  license: {
    id: string;
    name: string;
    url: string | null;
  };
  client_side: string;
  server_side: string;
  downloads: number;
  followers: number;
  categories: string[];
  additional_categories: [];
  game_versions: string[];
  loaders: string[];
  versions: string[];
  icon_url: string;
  issues_url: string;
  source_url: string;
  wiki_url: string | null;
  discord_url: string;
  donation_urls: string[];
  gallery: {
    url: string;
    featured: boolean;
    title: string;
    description: string;
    created: string;
    ordering: number;
  }[];
  color: number;
  thread_id: string;
  monetization_status: string;
};

export type ModrinthGameVersion = {
  version: string;
  version_type: string;
  data: string;
  major: boolean;
}

export class Modrinth {
  static apiRoot = "https://api.modrinth.com/v2";

  static async searchMods(
    q: string,
    version: string,
    loader: Loader,
    offset = 0,
    limit = 12,
  ) {
    const facets = [
      `"versions:${version}"`,
      '"project_type:mod"',
    ];

    if (loader && loader !== "vanilla" && loader !== "unset") {
      facets.push(`"categories:${loader}"`);
    }
    const qString = `/search?query=${q}&facets=[[${
      facets.join("],[")
    }]]&offset=${offset * limit}&limit=${limit}`.trim();

    const res = await fetch(this.apiRoot + qString);
    return await res.json() as {
      hits: ModrinthProjectSearchResult;
      offset: number;
      limit: number;
      total_hits: number;
    };
  }

  static async getProject(id: string) {
    const res = await fetch(this.apiRoot + "/project/" + id);
    return await res.json() as ModrinthProject;
  }

  static async getGameVersions() {
    const res = await fetch(this.apiRoot + '/tag/game_version');
    return await res.json() as ModrinthGameVersion[];
  }
}
