import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts";
import { AccessDeniedError } from "@lib/errors.ts";
import { searchResource } from "@lib/search.ts";

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("types")?.split(",");
    const tags = url.searchParams?.get("tags")?.split(",");
    const authors = url.searchParams?.get("authors")?.split(",");

    const resources = await searchResource({
      q: url.searchParams.get("q") || "",
      types,
      tags,
      authors,
    });

    return json(resources);
  },
};
