import { useState, useEffect } from "react";
import loginFunction from "../../utils/login.js";
import getUser from "../../utils/getUser.js";
import { AuthContext } from "./AuthContext";
import logoutFunction from "../../utils/auth/logout.js"


export function AuthProvider({ children }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        (async () => {
            const u = await getUser();
            setUser(u);
            setLoading(false);
        })();
    }, []);

    const login = async (email, password) => {
        const res = await loginFunction(email, password);
        if (!res || res.status !== 200) throw new Error("Login error");
        const u = await getUser();
        setUser(u);
        return res;
    };

    const logout = async () => {
        await logoutFunction();
        setUser(null);
    };

    const update = async () => {
        const u = await getUser();
        setUser(u);
    }

    return (
        <AuthContext.Provider value={{ user, loading, login, logout, update }}>
            {children}
        </AuthContext.Provider>
    );
}
