import getXSRFToken from "./getXSRF.js";

export default async function register(email, password, name, lastname, phone) {
    const csrfToken = await getXSRFToken();

    try {
        const response = await fetch(`http://${import.meta.env.VITE_API_URL}/api/users/register`, {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'X-XSRF-TOKEN': csrfToken,
                'Accept': 'application/json'
            },
            body: JSON.stringify({ email, password, name, lastname, phone }),
        });

        const data = await response.json();

        if (!response.ok) {
            if (response.status === 422) {
                return {
                    status: 422,
                    errors: data.errors
                };
            }

            throw new Error(`Erreur HTTP ${response.status}`);
        }

        return { status: response.status, data };

    } catch (error) {
        return { status: "error", error };
    }
}
