import { createContext, useContext, useEffect, useState } from 'react';

export type AuthUser = {
  id: string;
  username: string;
  displayName: string;
  role: string;
  status?: string;
};

type AuthState = { loading: boolean; user: AuthUser | null };

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [state, setState] = useState<AuthState>({ loading: true, user: null });

  useEffect(() => {
    void fetch('/auth/status', { credentials: 'include' })
      .then((r) => r.json())
      .then((auth: { authenticated: boolean; user?: AuthUser }) => {
        setState({ loading: false, user: auth.authenticated ? (auth.user ?? null) : null });
      })
      .catch(() => setState({ loading: false, user: null }));
  }, []);

  return <AuthContext.Provider value={state}>{children}</AuthContext.Provider>;
}

export const useAuth = () => useContext(AuthContext);
