import { MenuEntry } from "@islands/KMenu/types.ts";
import { TMDBSeries } from "@lib/types.ts";
import { getCookie } from "@lib/string.ts";
import { Series } from "@lib/resource/series.ts";

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

    const query = series.name;

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

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

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

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

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