// requireAuthHook.js
import { API_URL } from "@/config";

export const requireAuthHook = async (Astro) => {
  try {
    const cookieHeader = Astro.request.headers.get("cookie") ?? "";
    let res = await fetch(`${API_URL}/auth/id`, {
      headers: { Cookie: cookieHeader },
      credentials: "include",
    });

    if (res.status === 401) {
      const refreshRes = await fetch(`${API_URL}/auth/refresh`, {
        method: "POST",
        headers: { Cookie: cookieHeader },
        credentials: "include",
      });

      if (!refreshRes.ok) {
        console.error("Token refresh failed", refreshRes.status);
        return null;
      }

      const setCookieHeader = refreshRes.headers.get("set-cookie");
      let newCookieHeader = cookieHeader;

      if (setCookieHeader) {
        const cookiesArray = setCookieHeader.split(/,(?=\s*\w+=)/);
        cookiesArray.forEach((c) => Astro.response.headers.append("set-cookie", c));

        newCookieHeader = cookiesArray.map(c => c.split(";")[0]).join("; ");
      } else {
        console.error("No set-cookie header found in refresh response");
        return null;
      }

      res = await fetch(`${API_URL}/auth/id`, {
        headers: { Cookie: newCookieHeader },
        credentials: "include",
      });
    }

    if (!res.ok) {
      console.error("Failed to fetch user ID after token refresh", res.status);
      return null;
    }

    const user = await res.json();
    return user;

  } catch (err) {
    console.error("[SSR] requireAuthHook error:", err);
    return null;
  }
};
