import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts";
import { getAllMovies, Movie } from "@lib/resource/movies.ts";
import { Article, getAllArticles } from "@lib/resource/articles.ts";
import { getAllRecipes, Recipe } from "@lib/resource/recipes.ts";
import { AccessDeniedError } from "@lib/errors.ts";

const isResource = (
  item: Movie | Article | Recipe | boolean,
): item is Movie | Article | Recipe => {
  return !!item;
};

export const handler: Handlers = {
  async GET(req, ctx) {
    const session = ctx.state.session;
    if (!session) {
      throw new AccessDeniedError();
    }

    const url = new URL(req.url);

    const types = url.searchParams.get("type")?.split(", ");

    let resources = (await Promise.all([
      (!types || types.includes("movie")) && getAllMovies(),
      (!types || types.includes("article")) && getAllArticles(),
      (!types || types.includes("recipe")) && getAllRecipes(),
    ])).flat().filter(isResource);

    const tags = url.searchParams?.get("tags")?.split(",");
    if (tags?.length) {
      resources = resources.filter((r) => {
        return tags?.every((t) => r.tags.includes(t));
      });
    }

    const authors = url.searchParams?.get("author")?.split(",");
    if (authors?.length) {
      resources = resources.filter((r) => {
        return r?.meta?.author && authors.includes(r?.meta?.author);
      });
    }

    return json(resources);
  },
};
