import * as cache from "@lib/cache/cache.ts";
import { MovieDb } from "https://esm.sh/moviedb-promise@3.4.1";
const moviedb = new MovieDb(Deno.env.get("TMDB_API_KEY") || "");

const CACHE_INTERVAL = 1000 * 60 * 24 * 30;

export const searchMovie = (query: string, year?: number) =>
  cache.cacheFunction({
    fn: () => moviedb.searchMovie({ query, year }),
    id: `query:moviesearch:${query}${year ? `-${year}` : ""}`,
    options: {
      expires: CACHE_INTERVAL,
    },
  });

export const searchTVShow = (query: string) =>
  cache.cacheFunction(
    {
      fn: () => moviedb.searchTv({ query }),
      id: `query:tvshowsearch:${query}`,
      options: {
        expires: CACHE_INTERVAL,
      },
    },
  );

export const getMovie = (id: number) =>
  cache.cacheFunction({
    fn: () => moviedb.movieInfo({ id }),
    id: `query:movie:${id}`,
    options: {
      expires: CACHE_INTERVAL,
    },
  });

export const getSeries = (id: number) =>
  cache.cacheFunction({
    fn: () => moviedb.tvInfo({ id }),
    id: `query:tvshow:${id}`,
    options: {
      expires: CACHE_INTERVAL,
    },
  });

export const getMovieCredits = (id: number) =>
  cache.cacheFunction({
    fn: () => moviedb.movieCredits(id),
    id: `query:moviecredits:${id}`,
    options: {
      expires: CACHE_INTERVAL,
    },
  });

export const getSeriesCredits = (id: number) =>
  cache.cacheFunction({
    fn: () => moviedb.tvCredits(id),
    id: `query:tvshowcredits:${id}`,
    options: {
      expires: CACHE_INTERVAL,
    },
  });

export async function getMovieGenre(id: number) {
  const genres = await cache.get("/genres/movies");
  return moviedb.genreTvList();
}

export async function getSeriesGenre(id: number) {
  const genres = await cache.get("/genres/series");
}

export async function getMoviePoster(id: string): Promise<ArrayBuffer> {
  const posterUrl = `https://image.tmdb.org/t/p/original/${id}`;
  const response = await fetch(posterUrl);
  const poster = await response.arrayBuffer();
  return poster;
}
