import AsyncStorage from "@react-native-async-storage/async-storage";
import * as React from "react";

interface User {
    email: string;
}

interface AuthContextValue {
    user: User | null;
    login: (email: string, password: string) => Promise<void>;
    logout: () => void;
}

const authContext = React.createContext<AuthContextValue | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = React.useState<User | null>(null);
    
    const login = async (email: string, password: string) => {
        const fakeUser = { email };

        await AsyncStorage.setItem("user", JSON.stringify(fakeUser));
        setUser(fakeUser);
    }

    const logout = async () => {
        await AsyncStorage.removeItem("user");
        setUser(null);
    }

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

export function useAuth() {
    const context = React.useContext(authContext);
    if(!context) {
        throw new Error("useAuth must be inside AuthProvider");
    }
    return context;
}



