import type { User } from '@/types';

const USER_KEY = 'pos_grosir_user';
const LEGACY_TOKEN_KEY = 'pos_grosir_token';

/**
 * Session-cookie auth (Sanctum SPA): credentials live in httpOnly cookies.
 * We only cache non-sensitive user profile for UI snappiness.
 */

function storage(): Storage | null {
  if (typeof window === 'undefined') return null;
  try {
    return window.sessionStorage;
  } catch {
    return null;
  }
}

// ============================================================
// User cache (not credentials)
// ============================================================
export function getStoredUser(): User | null {
  const s = storage();
  if (!s) return null;
  const raw = s.getItem(USER_KEY) ?? (() => {
    try {
      return window.localStorage.getItem(USER_KEY);
    } catch {
      return null;
    }
  })();
  if (!raw) return null;
  try {
    if (!s.getItem(USER_KEY)) {
      s.setItem(USER_KEY, raw);
      try {
        window.localStorage.removeItem(USER_KEY);
      } catch {
        /* ignore */
      }
    }
    return JSON.parse(raw) as User;
  } catch {
    return null;
  }
}

export function setStoredUser(user: User): void {
  const s = storage();
  if (!s) return;
  try {
    s.setItem(USER_KEY, JSON.stringify(user));
    window.localStorage?.removeItem(USER_KEY);
    // Wipe legacy bearer tokens if any remain
    s.removeItem(LEGACY_TOKEN_KEY);
    window.localStorage?.removeItem(LEGACY_TOKEN_KEY);
  } catch {
    /* ignore */
  }
}

export function removeStoredUser(): void {
  try {
    window.sessionStorage?.removeItem(USER_KEY);
    window.localStorage?.removeItem(USER_KEY);
    window.sessionStorage?.removeItem(LEGACY_TOKEN_KEY);
    window.localStorage?.removeItem(LEGACY_TOKEN_KEY);
  } catch {
    /* ignore */
  }
}

/**
 * Bearer tokens are NOT stored in sessionStorage (XSS risk).
 * SPA uses httpOnly session cookies only. Memory-only holder for rare
 * non-browser tooling — never persist to disk/storage.
 */
let memoryToken: string | null = null;

export function getToken(): string | null {
  // Always purge any legacy persisted tokens
  try {
    window.sessionStorage?.removeItem(LEGACY_TOKEN_KEY);
    window.localStorage?.removeItem(LEGACY_TOKEN_KEY);
  } catch {
    /* ignore */
  }
  return memoryToken;
}

export function setToken(token: string): void {
  memoryToken = token;
  try {
    window.sessionStorage?.removeItem(LEGACY_TOKEN_KEY);
    window.localStorage?.removeItem(LEGACY_TOKEN_KEY);
  } catch {
    /* ignore */
  }
}

export function removeToken(): void {
  memoryToken = null;
  try {
    window.sessionStorage?.removeItem(LEGACY_TOKEN_KEY);
    window.localStorage?.removeItem(LEGACY_TOKEN_KEY);
  } catch {
    /* ignore */
  }
}

// ============================================================
// Auth Helpers
// ============================================================

/** Soft check — real auth is validated via /auth/me */
export function isAuthenticated(): boolean {
  return !!getStoredUser();
}

export function clearAuth(): void {
  removeToken();
  removeStoredUser();
}
