import { getApiBaseUrl } from "@/components/main/BaseUrl";
import Cookies from "js-cookie";
import {
  getRegistrationRoute,
  resolveRegistrationRedirect,
} from "@/lib/auth/registrationRoutes";

export type RegisterStatusResponse = {
  step?: string;
  page?: "home" | "auth-page";
  registrationComplete?: boolean;
};

export async function fetchRegisterStatus(): Promise<RegisterStatusResponse | null> {
  const token = Cookies.get("token");
  if (!token) return null;

  try {
    const response = await fetch(`${getApiBaseUrl()}/register/status`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      cache: "no-store",
    });

    if (!response.ok) return null;

    return (await response.json()) as RegisterStatusResponse;
  } catch {
    return null;
  }
}

export async function resolveAuthenticatedEntryRedirect(
  redirectParam?: string | null
): Promise<string> {
  const status = await fetchRegisterStatus();
  if (!status) {
    return redirectParam &&
      redirectParam.startsWith("/") &&
      !redirectParam.startsWith("//")
      ? redirectParam
      : "/";
  }

  if (status.page === "home" || status.registrationComplete) {
    return redirectParam &&
      redirectParam.startsWith("/") &&
      !redirectParam.startsWith("//")
      ? redirectParam
      : "/";
  }

  if (redirectParam) {
    const registrationPath = redirectParam.split("?")[0];
    const allowed = resolveRegistrationRedirect(
      registrationPath,
      status.step
    );
    if (allowed === null) {
      return redirectParam;
    }
  }

  return getRegistrationRoute(status.step);
}
