import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts";
import * as tmdb from "@lib/tmdb.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import { isString, safeFileName } from "@lib/string.ts";
import { createDocument } from "@lib/documents.ts";
import { AccessDeniedError } from "@lib/errors.ts";
import { createSeries, getSeries, Series } from "@lib/resource/series.ts";

export const handler: Handlers = {
  async GET(_, ctx) {
    const series = await getSeries(ctx.params.name);
    return json(series);
  },
  async POST(_, ctx) {
    const session = ctx.state.session;
    if (!session) {
      throw new AccessDeniedError();
    }

    const tmdbId = parseInt(ctx.params.name);

    const seriesDetails = await tmdb.getSeries(tmdbId);
    const seriesCredits = await tmdb.getSeriesCredits(tmdbId);

    const releaseDate = seriesDetails.first_air_date;
    const posterPath = seriesDetails.poster_path;
    const director =
      seriesCredits?.crew?.filter?.((person) => person.job === "Director")[0] ||
      seriesDetails.created_by?.[0];

    let finalPath = "";
    const name = seriesDetails.name || seriesDetails.original_name ||
      ctx.params.name;
    if (posterPath) {
      const poster = await tmdb.getMoviePoster(posterPath);
      const extension = fileExtension(posterPath);

      finalPath = `Media/series/images/${
        safeFileName(name)
      }_cover.${extension}`;
      await createDocument(finalPath, poster);
    }

    const metadata = { tmdbId } as Series["meta"];
    if (releaseDate) {
      metadata.date = new Date(releaseDate);
    }
    if (finalPath) {
      metadata.image = finalPath;
    }
    if (director) {
      metadata.author = director.name;
    }

    const tags: string[] = [];
    if (seriesDetails.genres) {
      tags.push(
        ...seriesDetails.genres.map((g) => g.name?.toLowerCase()).filter(
          isString,
        ),
      );
    }

    const series: Series = {
      id: name,
      name: name,
      tags,
      type: "series",
      description: "",
      meta: metadata,
    };

    await createSeries(name, series);

    return json(series);
  },
};
