import { optima } from "$lib";
import { redirect, type Handle } from "@sveltejs/kit";
import { access } from "fs";
import { a } from "vitest/dist/chunks/suite.d.FvehnV49.js";

export const handle: Handle = async ({ event, resolve }) => {
  const accessToken = event.cookies.get("access_token");
  const refreshToken = event.cookies.get("refresh_token");

  event.locals.ession = {
    accessToken: accessToken || "",
    refreshToken: refreshToken || "",
  };

  if (event.url.pathname === "/logout") {
    event.cookies.delete("access_token", { path: "/" });
    event.cookies.delete("refresh_token", { path: "/" });

    redirect(303, "/login");

    return resolve(event);
  }

  if (
    event.url.pathname.startsWith("/login") &&
    optima.user.isLoggedInServer(event)
  ) {
    return redirect(303, "/");
  }

  if (event.url.pathname.startsWith("/login")) {
    return await resolve(event);
  }

  if (!accessToken || !refreshToken) {
    optima.user.logout(event);
    return resolve(event);
  }

  try {
    if (accessToken && refreshToken) {
      const newSession = await optima.user.refreshSession(refreshToken);

      event.cookies.set("access_token", newSession.accessToken, {
        httpOnly: true,
        path: "/",
      });
      event.cookies.set("refresh_token", newSession.refreshToken, {
        httpOnly: true,
        path: "/",
      });
    }
  } catch (err) {
    console.trace(err);

    optima.user.logout(event);
  } finally {
    return await resolve(event);
  }
};
