import Cookies from "js-cookie";
import {
  readLocalStorage,
  writeLocalStorage,
  removeLocalStorage,
} from "@/lib/safeStorage";

const TOKEN_KEY = "token";
const LOGIN_GRACE_KEY = "auth_login_grace_until";

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:",
});

async function syncServerCookie(token: string): Promise<boolean> {
  try {
    const res = await fetch("/api/auth/session", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token }),
      credentials: "same-origin",
    });
    return res.ok;
  } catch {
    return false;
  }
}

/** پس از ورود، برای جلوگیری از logout اشتباه روی 401های موقت */
export function markLoginGracePeriod(ms = 8000): void {
  if (typeof window === "undefined") return;
  sessionStorage.setItem(LOGIN_GRACE_KEY, String(Date.now() + ms));
}

export function isInLoginGracePeriod(): boolean {
  if (typeof window === "undefined") return false;
  const until = Number(sessionStorage.getItem(LOGIN_GRACE_KEY) || 0);
  return Date.now() < until;
}

/** همگام‌سازی کوکی کلاینت با Route Handler (برای middleware) */
export async function ensureAuthSessionSynced(): Promise<boolean> {
  if (typeof window === "undefined") return false;
  const token = Cookies.get(TOKEN_KEY);
  if (!token) return false;
  return syncServerCookie(token);
}

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

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

  let synced = await syncServerCookie(token);
  if (!synced) {
    synced = await syncServerCookie(token);
  }

  if (!synced) {
    console.warn("[auth] server session cookie sync failed");
  }

  markLoginGracePeriod();

  if (meta?.id) writeLocalStorage("id", String(meta.id));
  if (meta?.user_type) writeLocalStorage("usertype", meta.user_type);
  if (meta?.step) writeLocalStorage("step", meta.step);
  if (meta?.auth_provider) {
    writeLocalStorage("auth_provider", meta.auth_provider);
  }
  if (meta?.email) writeLocalStorage("email", meta.email);
}

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

  if (typeof window !== "undefined") {
    sessionStorage.removeItem(LOGIN_GRACE_KEY);
  }

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

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

export function getStoredUserId(): string {
  return readLocalStorage("id") ?? "";
}

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

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

export const PROTECTED_APP_PATHS = ["/settings", "/new-post", "/new-project"];

export function isProtectedAppPath(path: string): boolean {
  return PROTECTED_APP_PATHS.some((prefix) => path.startsWith(prefix));
}
