'use client';

import { useEffect, type ReactNode } from 'react';
import { authApi } from '@/lib/auth';
import { useAuthStore } from '@/lib/store/auth';

export function AuthProvider({ children }: { children: ReactNode }) {
  const setUser = useAuthStore((s) => s.setUser);
  const setStatus = useAuthStore((s) => s.setStatus);

  useEffect(() => {
    // B1 — the token is HttpOnly and unreadable from JS, so probe the session by
    // calling `me()` directly. A 401 here is expected for guests and is handled
    // locally (the response interceptor skips the redirect for this endpoint).
    authApi
      .me()
      .then(setUser)
      .catch(() => setStatus('guest'));
  }, [setUser, setStatus]);

  return <>{children}</>;
}

export function useAuth() {
  const user = useAuthStore((s) => s.user);
  const status = useAuthStore((s) => s.status);
  return { user, status };
}
