import { MenuEntry } from "@islands/KMenu/types.ts";
import { Movie } from "@lib/resource/movies.ts";
import { TMDBMovie } from "@lib/types.ts";
import { getCookie } from "@lib/string.ts";

export const addMovieInfos: MenuEntry = {
  title: "Add Movie infos",
  meta: "",
  icon: "IconReportSearch",
  cb: async (state, context) => {
    state.activeState.value = "loading";
    const movie = context as Movie;

    const query = movie.name;

    const response = await fetch(
      `/api/tmdb/query?q=${encodeURIComponent(query)}`,
    );

    const json = await response.json() as TMDBMovie[];

    const menuID = `result/${movie.name}`;

    state.menus[menuID] = {
      title: "Select",
      entries: json.map((m) => ({
        title: `${m.title} released ${m.release_date}`,
        cb: async () => {
          state.activeState.value = "loading";
          await fetch(`/api/movies/enhance/${movie.name}/`, {
            method: "POST",
            body: JSON.stringify({ tmdbId: m.id }),
          });
          state.visible.value = false;
          state.activeState.value = "normal";
          window.location.reload();
        },
      })),
    };

    state.activeMenu.value = menuID;
    state.commandInput.value = "";
    state.activeState.value = "normal";
  },
  visible: () => {
    const loc = globalThis["location"];
    if (!getCookie("session_cookie")) return false;
    return (loc?.pathname?.includes("movie") &&
      !loc.pathname.endsWith("movies"));
  },
};
