import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import type { IVerifyOtp } from "@/types/types";
import { setAuthSession } from "@/lib/auth/session";
import { AUTH_SUCCESS_DELAY_MS, pause } from "@/lib/auth/feedback";
import { getRegistrationRoute } from "@/lib/auth/registrationRoutes";

export function getSafeRedirectPath(): string {
  if (typeof window === "undefined") return "/";
  const redirect = new URLSearchParams(window.location.search).get("redirect");
  if (redirect && redirect.startsWith("/") && !redirect.startsWith("//")) {
    return redirect;
  }
  return "/";
}

export async function navigateIncompleteRegistration(
  router: AppRouterInstance,
  step?: string
) {
  router.push(getRegistrationRoute(step));
}

export async function completeLogin(
  router: AppRouterInstance,
  response: IVerifyOtp,
  options?: { redirectTo?: string }
): Promise<boolean> {
  if (!response?.token) return false;

  await setAuthSession(response.token, {
    id: response.id,
    user_type: response.user_type,
    step: response.step,
    auth_provider: response.auth_provider,
    email: response.email ?? undefined,
  });

  await pause(AUTH_SUCCESS_DELAY_MS);
  router.refresh();

  if (response.page === "home") {
    router.push(options?.redirectTo ?? getSafeRedirectPath());
    return true;
  }

  if (response.page === "auth-page") {
    await navigateIncompleteRegistration(router, response.step);
    return true;
  }

  return false;
}

export function getAxiosErrorMessage(error: unknown): string {
  const data = (
    error as {
      response?: { data?: { message?: string; en_message?: string } };
    }
  )?.response?.data;

  if (data?.en_message === "Not allowed by CORS") {
    return "خطا در اتصال به سرور. صفحه را رفرش کنید و دوباره تلاش کنید.";
  }
  if (data?.message) return data.message;
  if ((error as Error)?.message === "Network Error") {
    return "خطا در ارتباط با سرور. اتصال اینترنت را بررسی کنید.";
  }
  return "نام کاربری یا کلمه عبور اشتباه است.";
}
