import { BASE_API_URI } from "$lib/utils/constants.js";

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
  if (event.locals.user) {
    // if there is already a user  in session load page as normal
    return await resolve(event);
  }

  // get cookies from browser
  const jwt = event.cookies.get("jwt");

  if (!jwt) {
    // if there is no jwt load page as normal
    return await resolve(event);
  }
  const response = await fetch(`${BASE_API_URI}/backend/users/current`, {
    credentials: "include",
    headers: {
      Cookie: `jwt=${jwt}`,
    },
  });
  if (!response.ok) {
    // Clear the invalid JWT cookie
    event.cookies.delete("jwt", { path: "/" });
    return await resolve(event);
  }
  // find the user based on the jwt

  const userData = await response.json();

  // Check if the server sent a new token
  const newToken = response.headers.get("Set-Cookie");
  if (newToken) {
    const match = newToken.match(/jwt=([^;]+)/);
    if (match) {
      event.cookies.set("jwt", match[1], {
        path: "/",
        httpOnly: true,
        secure: process.env.NODE_ENV === "production", // Secure in production
        sameSite: "lax",
        maxAge: 5 * 24 * 60 * 60, // 5 days in seconds
      });
    }
  }

  event.locals.user = userData;
  if (event.locals.user.date_of_birth) {
    event.locals.user.date_of_birth =
      event.locals.user.date_of_birth.split("T")[0];
  }
  if (event.locals.user.membership) {
    if (event.locals.user.membership.start_date) {
      event.locals.user.membership.start_date =
        event.locals.user.membership.start_date.split("T")[0];
    }
    if (event.locals.user.membership.end_date) {
      event.locals.user.membership.end_date =
        event.locals.user.membership.end_date.split("T")[0];
    }
  }
  if (
    event.locals.user.bank_account &&
    event.locals.user.bank_account.mandate_date_signed
  ) {
    event.locals.user.bank_account.mandate_date_signed =
      event.locals.user.bank_account.mandate_date_signed.split("T")[0];
  }

  // load page as normal
  return await resolve(event);
}
