const API_URL = process.env.NEXT_PUBLIC_API_URL;

type ChangeEmailResponse =
    | { data: { email: string }; error: null }
    | { data: null; error: { general: string } };

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

        const data = await res.json().catch(() => null);

        if (!res.ok) {
            const detail = data?.detail;

            return {
                data: null,
                error: {
                    general:
                        typeof detail === 'string'
                            ? detail
                            : detail?.msg || 'Ошибка смены почты',
                },
            };
        }

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