import Cookies from "js-cookie";

const TOKEN_KEY = "token";

export type AuthUserMeta = {
  id?: string;
  user_type?: string;
  step?: string;
  auth_provider?: string;
  email?: string;
};

const cookieOptions = (): Cookies.CookieAttributes => ({
  path: "/",
  expires: 365,
  sameSite: "Lax",
  secure: typeof window !== "undefined" && window.location.protocol === "https:",
});

/** ذخیره توکن در کوکی مرورگر + Route Handler سرور (برای middleware) */
export async function setAuthSession(
  token: string,
  meta?: AuthUserMeta
): Promise<void> {
  if (!token) return;

  Cookies.set(TOKEN_KEY, token, cookieOptions());

  await fetch("/api/auth/session", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ token }),
    credentials: "same-origin",
  });

  if (meta?.id) localStorage.setItem("id", meta.id);
  if (meta?.user_type) localStorage.setItem("usertype", meta.user_type);
  if (meta?.step) localStorage.setItem("step", meta.step);
  if (meta?.auth_provider) localStorage.setItem("auth_provider", meta.auth_provider);
  if (meta?.email) localStorage.setItem("email", meta.email);
}

/** پاک کردن کامل session */
export async function clearAuthSession(): Promise<void> {
  Cookies.remove(TOKEN_KEY, { path: "/" });

  try {
    await fetch("/api/auth/session", {
      method: "DELETE",
      credentials: "same-origin",
    });
  } catch {
    // ignore
  }

  localStorage.removeItem("id");
  localStorage.removeItem("mobile");
  localStorage.removeItem("otp");
  localStorage.removeItem("token");
  localStorage.removeItem("usertype");
  localStorage.removeItem("first_name");
  localStorage.removeItem("last_name");
  localStorage.removeItem("username");
  localStorage.removeItem("step");
  localStorage.removeItem("auth_provider");
  localStorage.removeItem("email");
}

export function getStoredUserId(): string {
  if (typeof window === "undefined") return "";
  return localStorage.getItem("id") ?? "";
}

export function getAuthToken(): string | undefined {
  if (typeof window === "undefined") return undefined;
  return Cookies.get(TOKEN_KEY);
}

export function isAuthenticated(): boolean {
  return Boolean(getAuthToken());
}
