import { Handlers } from "$fresh/server.ts";
import { createMovie, getMovie, Movie } from "@lib/resource/movies.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";

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

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

    const movieDetails = await tmdb.getMovie(tmdbId);
    const movieCredits = await tmdb.getMovieCredits(tmdbId);

    const releaseDate = movieDetails.release_date;
    const posterPath = movieDetails.poster_path;
    const director = movieCredits?.crew?.filter?.((person) =>
      person.job === "Director"
    )[0];

    movieDetails.overview;

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

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

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

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

    const movie: Movie = {
      id: name,
      name: name,
      type: "movie",
      description: "",
      tags,
      meta: metadata,
    };

    await createMovie(name, movie);

    return json(movie);
  },
};
