import { MiddlewareHandlerContext, Status } from "$fresh/server.ts";

export const handler = async (
  req: Request,
  ctx: MiddlewareHandlerContext<Record<string, unknown>>,
) => {
  const authRequired = Deno.env.get("AUTH_REQUIRED") === "true";
  if (authRequired) {
    const login = ctx.state["login"];
    if (!login) {
      return new Response(null, {
        status: Status.Found,
        headers: {
          Location: `/login?redirect=${encodeURIComponent(req.url)}`,
        },
      });
    }
  }
  return await ctx.next();
};
