import {
  createContext,
  useContext,
  useState,
  useEffect,
  type ReactNode,
} from "react";
import { auth } from "../api";
import type { UserInfo } from "../types";

interface AuthContextValue {
  user: UserInfo | null;
  authLoading: boolean;
  setUser: (user: UserInfo | null) => void;
  refreshUser: () => Promise<void>;
}

const AuthContext = createContext<AuthContextValue | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<UserInfo | null>(null);
  const [authLoading, setAuthLoading] = useState(true);

  async function refreshUser() {
    const u = await auth.me();
    setUser(u);
  }

  useEffect(() => {
    auth.me().then((u) => {
      setUser(u);
      setAuthLoading(false);
    });
  }, []);

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

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth must be used within AuthProvider");
  return ctx;
}
