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
  if (locals.user) {
    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 }) => {
    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) {
      let errorMessage = `HTTP error! status: ${res.status}`;
      try {
        const errorData = await res.json();
        errorMessage = errorData.error || errorMessage;
      } catch (parseError) {
        console.error("Failed to parse error response:", parseError);
        errorMessage = await res.text(); // Get the raw response text if JSON parsing fails
      }
      console.error("Login failed:", errorMessage);
      return fail(res.status, {
        errors: [{ error: errorMessage, id: Date.now() }],
      });
    }

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

    // Check for the cookie in the response headers
    const setCookieHeader = res.headers.get("set-cookie");
    console.log("Set-Cookie header:", setCookieHeader);

    if (setCookieHeader) {
      // Parse the Set-Cookie header to get the JWT
      const jwtCookie = setCookieHeader.split(";")[0];
      const [cookieName, cookieValue] = jwtCookie.split("=");
      if (cookieName.trim() === "jwt") {
        console.log("JWT cookie found in response");
        cookies.set("jwt", cookieValue.trim(), {
          path: "/",
          httpOnly: true,
          sameSite: "strict",
          secure: process.env.NODE_ENV === "production",
        });
      } else {
        console.log("JWT cookie not found in response");
      }
    } else {
      console.log("No Set-Cookie header in response");
    }

    console.log("Redirecting to:", next || "/");
    throw redirect(303, next || "/");
  },
  //   if (!res.ok) {
  //     const response = await res.json();
  //     const errors = formatError(response.error);
  //     return fail(400, { errors: errors });
  //   }

  //   throw redirect(303, next || "/");
  // },
};
