import { useState, useEffect } from "react";

export interface AuthUser {
    discordId: string;
    username: string;
    avatar: string | null;
    role: "admin" | "player";
}

interface AuthState {
    loading: boolean;
    user: AuthUser | null;
    enrolled: boolean;
}

export function useAuth(): AuthState & { logout: () => Promise<void> } {
    const [state, setState] = useState<AuthState>({ loading: true, user: null, enrolled: true });

    useEffect(() => {
        fetch("/auth/me", { credentials: "same-origin" })
            .then((r) => r.json())
            .then((data: { authenticated: boolean; enrolled: boolean; user?: AuthUser }) => {
                setState({
                    loading: false,
                    user: data.authenticated ? data.user! : null,
                    enrolled: data.enrolled ?? true,
                });
            })
            .catch(() => setState({ loading: false, user: null, enrolled: true }));
    }, []);

    const logout = async () => {
        await fetch("/auth/logout", { method: "POST", credentials: "same-origin" });
        setState({ loading: false, user: null, enrolled: true });
    };

    return { ...state, logout };
}
