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";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";
import { translateCommon } from "@/lib/i18n/translate";

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
) {
  navigateAfterAuth(getRegistrationRoute(step));
}

function navigateAfterAuth(target: string): void {
  if (typeof window === "undefined") return;
  window.location.assign(target);
}

function readString(value: unknown): string | undefined {
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
}

/** Normalize login payloads from OTP, username, or Google auth endpoints. */
export function parseLoginResponse(raw: unknown): IVerifyOtp {
  if (!raw || typeof raw !== "object") {
    return { message: "" };
  }

  const obj = raw as Record<string, unknown>;

  if (obj.data && typeof obj.data === "object" && !readString(obj.token)) {
    return parseLoginResponse(obj.data);
  }

  const token =
    readString(obj.token) ||
    readString(obj.accessToken) ||
    readString(obj.access_token);

  const page =
    obj.page === "home" || obj.page === "auth-page" ? obj.page : undefined;

  return {
    message: readString(obj.message) || "",
    token,
    user_type:
      typeof obj.user_type === "string"
        ? obj.user_type
        : obj.user_type === null
          ? null
          : undefined,
    step: readString(obj.step),
    page,
    id: obj.id != null ? String(obj.id) : undefined,
    auth_provider:
      obj.auth_provider === "google" ||
      obj.auth_provider === "mobile" ||
      obj.auth_provider === "instagram"
        ? obj.auth_provider
        : undefined,
    email:
      typeof obj.email === "string"
        ? obj.email
        : obj.email === null
          ? null
          : undefined,
    requires_2fa: Boolean(obj.requires_2fa),
    temp_token: readString(obj.temp_token),
    registrationComplete:
      typeof obj.registrationComplete === "boolean"
        ? obj.registrationComplete
        : undefined,
  };
}

function resolvePostLoginPage(response: IVerifyOtp): "home" | "auth-page" {
  if (response.page === "home" || response.page === "auth-page") {
    return response.page;
  }

  if (
    response.registrationComplete === true ||
    response.step === "complete" ||
    Boolean(response.user_type)
  ) {
    return "home";
  }

  return "auth-page";
}

export async function completeLogin(
  router: AppRouterInstance,
  rawResponse: IVerifyOtp | unknown,
  options?: { redirectTo?: string }
): Promise<boolean> {
  const response = parseLoginResponse(rawResponse);

  if (response.requires_2fa && response.temp_token) {
    if (typeof window !== "undefined") {
      sessionStorage.setItem("login_2fa_temp", response.temp_token);
      const redirect = options?.redirectTo ?? getSafeRedirectPath();
      window.location.assign(
        `/login-2fa?redirect=${encodeURIComponent(redirect)}`
      );
    }
    return true;
  }

  if (!response.token) return false;

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

  await pause(AUTH_SUCCESS_DELAY_MS);

  const page = resolvePostLoginPage(response);

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

  await navigateIncompleteRegistration(router, response.step);
  return true;
}

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

  if (data?.en_message === "Not allowed by CORS") {
    return translateCommon(lang, "errors.corsError");
  }
  if (data?.message) return data.message;
  if ((error as Error)?.message === "Network Error") {
    return translateCommon(lang, "errors.networkError");
  }
  return translateCommon(lang, "auth.wrongCredentials");
}

export function getLoginFailureMessage(
  rawResponse: unknown,
  lang: AppLanguage = DEFAULT_LANGUAGE
): string {
  const response = parseLoginResponse(rawResponse);

  if (response.message) return response.message;
  if (response.requires_2fa && !response.temp_token) {
    return translateCommon(lang, "auth.invalidServerResponse");
  }

  return translateCommon(lang, "auth.invalidServerResponse");
}
