import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from "react";
import { auth as authApi, global as globalApi } from "../api/client";
import type { GlobalSettings, User } from "../api/types";

type AuthContextValue = {
	user: User | null;
	loading: boolean;
	settings: GlobalSettings | null;
	setUser: (u: User | null) => void;
	refresh: () => Promise<void>;
	logout: () => Promise<void>;
};

const AuthContext = createContext<AuthContextValue>({
	user: null,
	loading: true,
	settings: null,
	setUser: () => {},
	refresh: async () => {},
	logout: async () => {},
});

export function AuthProvider({ children }: { children: ReactNode }) {
	const [user, setUser] = useState<User | null>(null);
	const [loading, setLoading] = useState(true);
	const [settings, setSettings] = useState<GlobalSettings | null>(null);

	const refresh = useCallback(async () => {
		try {
			const me = await authApi.me();
			setUser(me);
		} catch {
			setUser(null);
		}
	}, []);

	useEffect(() => {
		(async () => {
			globalApi.get().then(setSettings).catch(() => {});
			await refresh();
			setLoading(false);
		})();
	}, [refresh]);

	const logout = useCallback(async () => {
		await authApi.logout().catch(() => {});
		setUser(null);
	}, []);

	return (
		<AuthContext.Provider value={{ user, loading, settings, setUser, refresh, logout }}>
			{children}
		</AuthContext.Provider>
	);
}

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