// frontend/src/contexts/AuthContext.jsx
import React, { createContext, useState, useContext, useEffect } from 'react';
import api from '../services/api';

const AuthContext = createContext();

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

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

    useEffect(() => {
        checkAuth();
    }, []);

    const checkAuth = async () => {
        try {
            const response = await api.get('/auth/me');
            if (response.data.user_id) {
                setUser({ id: response.data.user_id, name: response.data.full_name });
            }
        } catch (error) {
            setUser(null);
        } finally {
            setLoading(false);
        }
    };

    const login = async (email, password) => {
        const response = await api.post('/auth/login', { email, password });
        if (response.data.success) {
            setUser({ id: response.data.user_id, name: response.data.full_name });
            return true;
        }
        throw new Error(response.data.error);
    };

    const register = async (email, password, fullName) => {
        const response = await api.post('/auth/register', { email, password, full_name: fullName });
        if (response.data.success) {
            setUser({ id: response.data.user_id, name: response.data.full_name });
            return true;
        }
        throw new Error(response.data.error);
    };

    const logout = async () => {
        await api.post('/auth/logout');
        setUser(null);
    };

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