import { useState, useEffect } from "react";
import loginFunction from "../../utils/auth/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();
            if(u.status === 200) setUser(u.data);
            setLoading(false);
        })();
    }, []);

    const login = async (email, password) => {
        const res = await loginFunction(email, password);
        const u = res.status === 200 ? await getUser() : null;
        if (u) setUser(u.data);
        return res;
    };


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

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

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