import { showToast } from "./components/domEl";

type SetupStatus = 'password_required' | '2fa_setup_required' | 'complete';
export interface AuthUser {
  id: number;
  name: string;
  email: string;
  role_id: number;
  setup_status: SetupStatus;
}


let _cachedUser: AuthUser | null | undefined = undefined;

export async function getAuthUser(forceRefresh = false): Promise<AuthUser | null> {
  if (!forceRefresh && _cachedUser !== undefined) {
    return _cachedUser;
  }

  try {
    const response = await fetch('/api/user', {
      credentials: 'include',
      headers: { 'Accept': 'application/json' },
    });

    console.log('getAuthUser status:', response.status); 
    const data = response.ok ? (await response.json() as AuthUser) : null;
    console.log('getAuthUser data:', data);
    
    _cachedUser = data;
  } catch {
    _cachedUser = null;
  }

  return _cachedUser;
}

export function clearAuthCache(): void {
  _cachedUser = undefined;
}

export async function isAuthenticated(): Promise<boolean> {
  return (await getAuthUser()) !== null;
}

export async function getCsrfCookie(): Promise<void> {
  await fetch('/sanctum/csrf-cookie', { credentials: 'include' });
}

export async function logoutUser(){
  await fetch('/api/logout', {
    method: 'POST',
    credentials: 'include',
    headers: { 'Accept': 'application/json' },
  });

  clearAuthCache();
  showToast('Logout effettuato. Verrai reindirizzato alla home...', 'success');
  setTimeout(() => { globalThis.location.href = '/'; }, 5000);
}