export const REGISTRATION_ENTRY_PATH = "/register";
export const REGISTRATION_OTP_PATH = "/register-otp";

export const REGISTRATION_STEP_PATHS = [
  "/register/username",
  "/register/password",
  "/register/fullname",
  "/register/complete",
  "/register/usertype",
] as const;

export type RegistrationStep =
  | "user_name"
  | "password"
  | "first_name"
  | "registration_choice"
  | "user_type"
  | "complete";

export function getRegistrationRoute(step?: string): string {
  switch (step) {
    case "user_name":
      return "/register/username";
    case "password":
      return "/register/password";
    case "first_name":
      return "/register/fullname";
    case "registration_choice":
      return "/register/complete";
    case "user_type":
      return "/register/complete";
    default:
      return "/register/username";
  }
}

export function normalizeRegistrationPath(pathname: string): string {
  const base = pathname.split("?")[0].replace(/\/$/, "") || "/";
  if (base.startsWith("/register/usertype")) return "/register/usertype";
  if (base.startsWith("/register/complete")) return "/register/complete";
  if (base.startsWith("/register/fullname")) return "/register/fullname";
  if (base.startsWith("/register/password")) return "/register/password";
  if (base.startsWith("/register/username")) return "/register/username";
  if (base === REGISTRATION_OTP_PATH) return REGISTRATION_OTP_PATH;
  if (base === REGISTRATION_ENTRY_PATH) return REGISTRATION_ENTRY_PATH;
  return base;
}

export function isRegistrationPath(pathname: string): boolean {
  const path = normalizeRegistrationPath(pathname);
  return (
    path === REGISTRATION_ENTRY_PATH ||
    path === REGISTRATION_OTP_PATH ||
    REGISTRATION_STEP_PATHS.includes(
      path as (typeof REGISTRATION_STEP_PATHS)[number]
    )
  );
}

export function requiresRegistrationToken(pathname: string): boolean {
  const path = normalizeRegistrationPath(pathname);
  return REGISTRATION_STEP_PATHS.includes(
    path as (typeof REGISTRATION_STEP_PATHS)[number]
  );
}

/** اگر کاربر مجاز به pathname فعلی نیست، مسیر درست را برمی‌گرداند */
export function resolveRegistrationRedirect(
  pathname: string,
  step?: string
): string | null {
  const normalized = normalizeRegistrationPath(pathname);

  if (!requiresRegistrationToken(normalized)) {
    return null;
  }

  if (!step || step === "complete") {
    return step === "complete" ? "/" : getRegistrationRoute(step);
  }

  const allowed = getRegistrationRoute(step);

  if (
    step === "registration_choice" &&
    (normalized === "/register/complete" || normalized === "/register/usertype")
  ) {
    return null;
  }

  if (normalized === allowed) {
    return null;
  }

  return allowed;
}

export function buildLoginRedirect(pathname: string): string {
  const safePath = pathname.startsWith("/") ? pathname : "/register";
  return `/login?redirect=${encodeURIComponent(safePath)}`;
}
