//routes/middleware-error-handler/_middleware.ts
import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { DomainError } from "@lib/errors.ts";
import { getCookies } from "https://deno.land/std@0.197.0/http/cookie.ts";
import { verify } from "https://deno.land/x/djwt@v2.2/mod.ts";
import * as cache from "@lib/cache/performance.ts";
import { JWT_SECRET } from "@lib/env.ts";

export async function handler(
  req: Request,
  ctx: MiddlewareHandlerContext,
) {
  try {
    performance.mark("a");
    const allCookies = getCookies(req.headers);
    const sessionCookie = allCookies["session_cookie"];
    if (!ctx.state.session && sessionCookie && JWT_SECRET) {
      try {
        const payload = await verify(sessionCookie, JWT_SECRET, "HS512");
        if (payload) {
          ctx.state.session = payload;
        }
      } catch (_err) {
        //
        console.log({ _err });
      }
    }

    const resp = await ctx.next();
    performance.mark("b");
    const b = performance.measure("a->b", "a", "b");
    cache.savePerformance(req.url, b.duration);
    return resp;
  } catch (error) {
    console.error("Error", error);

    if (error instanceof DomainError) {
      return new Response(error.statusText, {
        status: error.status,
      });
    }

    return new Response("Internal Server Error", {
      status: 500,
    });
  }
}
