import { Head, asset } from "$fresh/runtime.ts";
import { HandlerContext, Handlers, PageProps, Status } from "$fresh/server.ts";
import DocSearch from "../../islands/DocSearch.tsx";
import { Doc } from "../../src/collect.ts";
import { docCollector } from "../../src/store/doc.ts";

async function GET(req: Request, ctx: HandlerContext): Promise<Response> {
  const url = new URL(req.url);
  if (url.pathname.endsWith("/")) {
    url.pathname = url.pathname.slice(0, -1);
    return Response.redirect(url, Status.TemporaryRedirect);
  }
  const docs = docCollector.getDocs();
  return await ctx.render({ docs });
}

export const handler: Handlers = {
  GET,
};

export default function Docs(props: PageProps<{ docs: Doc[] }>) {
  const { docs } = props.data;
  return (
    <>
      <Head>
        <title>Simple file server - Doc</title>
        <link rel="stylesheet" href={asset("/base.css")} />
      </Head>
      <div class="p-4 mx-auto max-w-screen-md">
        <DocSearch docs={docs}></DocSearch>
      </div>
    </>
  );
}
