const API_URL = process.env.NEXT_PUBLIC_API_URL;

export const changeUsername = async (username: string) => {
    try {
        const res = await fetch(`${API_URL}/api/users/change-username`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username }),
            credentials: 'include',
        });

        if (!res.ok) {
            let errorData: any = null;

            try {
                errorData = await res.json();
            } catch {}

            return {
                data: null,
                error: {
                    general: errorData?.detail || 'Ошибка изменения никнейма',
                },
            };
        }

        const data = await res.json();

        return {
            data,
            error: null,
        };
    } catch (err: any) {
        return {
            data: null,
            error: { general: err.message },
        };
    }
};
