import createClient from "openapi-fetch";
import type { paths } from "./jellyfin.generated"; // generated by openapi-typescript
import { query } from "@solidjs/router";
import { Entry } from "../types";

const baseUrl = process.env.JELLYFIN_BASE_URL;
const client = createClient<paths>({
  baseUrl,
  headers: {
    Authorization: `MediaBrowser DeviceId="Streamarr", Token="${process.env.JELLYFIN_API_KEY}"`,
  },
});

export const listUsers = query(async () => {
  const { data, error } = await client.GET("/Users", {
    params: {},
  });

  return data ?? [];
}, "jellyfin.listUsers");

export const getItem = query(async (userId: string, itemId: string) => {
  const { data, error } = await client.GET("/Items/{itemId}", {
    params: {
      path: {
        itemId,
      },
      query: {
        userId,
        hasTmdbInfo: true,
        recursive: true,
        includeItemTypes: ["Movie", "Series"],
        fields: [
          "ProviderIds",
          "Genres",
          "DateLastMediaAdded",
          "DateCreated",
          "MediaSources",
        ],
      },
    },
  });

  return data?.Items ?? [];
}, "jellyfin.getItem");

export const getContinueWatching = query(
  async (userId: string): Promise<Entry[]> => {
    const { data, error } = await client.GET("/Users/{userId}/Items/Resume", {
      params: {
        path: {
          userId,
        },
        query: {
          mediaTypes: ["Video"],
          fields: ["ProviderIds", "Genres"],
        },
      },
    });

    const items = (data?.Items ?? []).map(({ Id, Name }) => ({
      id: Id,
      title: Name,
      thumbnail: `${baseUrl}/Items/${Id}/Images/Primary`,
    }));

    return items;
  },
  "jellyfin.continueWatching",
);
