import { createContext, useContext, type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';

interface User {
  sub: string;
  email?: string;
  name?: string;
  picture?: string;
}

interface AuthContextValue {
  user: User | null;
  isLoading: boolean;
}

const AuthContext = createContext<AuthContextValue>({ user: null, isLoading: true });

async function fetchMe(): Promise<User> {
  const res = await fetch('/api/auth/me');
  if (!res.ok) throw new Error('Unauthenticated');
  return res.json();
}

export function AuthProvider({ children }: { children: ReactNode }) {
  const { data: user = null, isLoading } = useQuery({
    queryKey: ['auth', 'me'],
    queryFn: fetchMe,
    retry: false,
    staleTime: 5 * 60 * 1000,
  });

  return (
    <AuthContext.Provider value={{ user, isLoading }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
