import { BASE_API_URI } from "$lib/utils/constants";
import { formatError } from "$lib/utils/helpers";
import { fail, redirect } from "@sveltejs/kit";

/** @type {import('./$types').PageServerLoad} */
export async function load({ locals }) {
  // redirect user if logged in
  console.log("loading login page");
  if (locals.user) {
    console.log("user is logged in");
    throw redirect(302, "/");
  }
}

/** @type {import('./$types').Actions} */
export const actions = {
  /**
   *
   * @param request - The request object
   * @param fetch - Fetch object from sveltekit
   * @param cookies - SvelteKit's cookie object
   * @returns Error data or redirects user to the home page or the previous page
   */
  login: async ({ request, fetch, cookies }) => {
    console.log("login action called");
    const data = await request.formData();
    const email = String(data.get("email"));
    const password = String(data.get("password"));
    const next = String(data.get("next"));
    /** @type {RequestInit} */
    const requestInitOptions = {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: email,
        password: password,
      }),
    };
    const res = await fetch(`${BASE_API_URI}/users/login`, requestInitOptions);
    console.log("Login response status:", res.status);
    console.log("Login response headers:", Object.fromEntries(res.headers));

    if (!res.ok) {
      const errorData = await res.json();
      const errors = formatError(errorData.errors);
      return fail(res.status, { errors });
    }

    const responseBody = await res.json();
    console.log("Login response body:", responseBody);

    // Extract the JWT from the response headers
    const setCookieHeader = res.headers.get("set-cookie");
    if (setCookieHeader) {
      const jwtMatch = setCookieHeader.match(/jwt=([^;]+)/);
      if (jwtMatch) {
        const jwtValue = jwtMatch[1];
        // Set the cookie for the client
        cookies.set("jwt", jwtValue, {
          path: "/",
          httpOnly: true,
          secure: process.env.NODE_ENV === "production", // Secure in production
          sameSite: "lax",
          maxAge: 5 * 24 * 60 * 60, // 5 days in seconds
        });
      }
    }

    console.log("Redirecting to:", next || "/");
    throw redirect(303, next || "/");
  },
};
