import { HandlerContext, Handlers } from "$fresh/server.ts";
import {
  createDocument,
  getDocument,
  transformDocument,
} from "@lib/documents.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import * as tmdb from "@lib/tmdb.ts";
import { parse, stringify } from "https://deno.land/std@0.194.0/yaml/mod.ts";
import { formatDate, safeFileName } from "@lib/string.ts";
import { json } from "@lib/helpers.ts";
import {
  AccessDeniedError,
  BadRequestError,
  NotFoundError,
} from "@lib/errors.ts";
import { createSeries, getSeries, Series } from "@lib/resource/series.ts";
import * as cache from "@lib/cache/cache.ts";

const isString = (input: string | undefined): input is string => {
  return typeof input === "string";
};

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

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

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

  const seriesDetails = await tmdb.getSeries(tmdbId);
  const seriesCredits = !series.meta.author &&
    await tmdb.getSeriesCredits(tmdbId);

  const releaseDate = seriesDetails.first_air_date;
  if (releaseDate && series.meta.date) {
    series.meta.date = new Date(releaseDate);
  }
  const posterPath = seriesDetails.poster_path;
  const director = seriesCredits &&
      seriesCredits.crew?.filter?.((person) => person.job === "Director")[0] ||
    seriesDetails?.created_by?.[0];
  if (director && director.name && !series.meta.author) {
    series.meta.author = director.name;
  }

  if (seriesDetails.genres) {
    series.tags = [
      ...new Set([
        ...series.tags.map((t) => t.toLowerCase()),
        ...seriesDetails.genres.map((g) => g.name?.toLowerCase()),
      ].filter(isString)),
    ];
  }

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

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

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

  return json(series);
};

export const handler: Handlers = {
  POST,
};
