import Cookies from "js-cookie";
import type { AuthUser } from "@/types/api/auth.types";

const LS_KEY = "dt_auth_user";
const UID_COOKIE = "user_id";

export function persistAuth(user: AuthUser) {
  localStorage.setItem(LS_KEY, JSON.stringify(user));
  Cookies.set(UID_COOKIE, String(user.id), { expires: 30, sameSite: "Lax" });
}

export function clearAuth() {
  localStorage.removeItem(LS_KEY);
  Cookies.remove(UID_COOKIE);
}

export function getStoredUser(): AuthUser | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = localStorage.getItem(LS_KEY);
    return raw ? (JSON.parse(raw) as AuthUser) : null;
  } catch {
    return null;
  }
}

export function isAuthenticatedClient(): boolean {
  if (typeof window === "undefined") return false;
  return !!Cookies.get(UID_COOKIE);
}
