import { HandlerContext, Handlers } from "$fresh/server.ts";
import { createDocument } from "@lib/documents.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import { createMovie, getMovie } from "@lib/resource/movies.ts";
import * as tmdb from "@lib/tmdb.ts";
import { isString, safeFileName } from "@lib/string.ts";
import { json } from "@lib/helpers.ts";
import {
  AccessDeniedError,
  BadRequestError,
  NotFoundError,
} from "@lib/errors.ts";
import * as cache from "@lib/cache/cache.ts";
import { createRecommendationResource } from "@lib/recommendation.ts";

const POST = async (
  req: Request,
  ctx: HandlerContext,
): Promise<Response> => {
  const session = ctx.state.session;
  if (!session) {
    throw new AccessDeniedError();
  }

  const movie = await getMovie(ctx.params.name);
  if (!movie) {
    throw new NotFoundError();
  }

  const body = await req.json();
  const name = ctx.params.name;
  const { tmdbId } = body;
  if (!name || !tmdbId) {
    throw new BadRequestError();
  }

  const movieDetails = await tmdb.getMovie(tmdbId);
  const movieCredits = !movie.meta.author &&
    await tmdb.getMovieCredits(tmdbId);

  const releaseDate = movieDetails.release_date;
  if (releaseDate && !movie.meta.date) {
    movie.meta.date = new Date(releaseDate);
  }

  const director = movieCredits?.crew?.filter?.((person) =>
    person.job === "Director"
  )[0];
  if (director && !movie.meta.author) {
    movie.meta.author = director.name;
  }

  if (movieDetails.genres) {
    movie.tags = [
      ...new Set([
        ...movie.tags.map((g) => g.toLowerCase()),
        ...movieDetails.genres.map((g) =>
          g.name?.toLowerCase().replaceAll(" ", "-")
        ),
      ].filter(isString)),
    ];
  }

  if (!movie.meta.tmdbId) {
    movie.meta.tmdbId = tmdbId;
  }

  let finalPath = "";
  const posterPath = movieDetails.poster_path;
  if (posterPath && !movie.meta.image) {
    const poster = await tmdb.getMoviePoster(posterPath);
    const extension = fileExtension(posterPath);

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

  await createMovie(movie.id, movie);

  cache.del(`documents:Media:movies:${name}.md`);

  createRecommendationResource(movie, movieDetails.overview);

  return json(movie);
};

export const handler: Handlers = {
  POST,
};
