const API_URL = process.env.NEXT_PUBLIC_API_URL;

export type ChangePasswordResponse =
    | { data: { success: true }; error: null }
    | { data: null; error: { general: string } };

export const changePassword = async (
    currentPassword: string,
    newPassword: string,
    repeatPassword: string,
): Promise<ChangePasswordResponse> => {
    try {
        const res = await fetch(`${API_URL}/api/users/password`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword,
                repeat_password: repeatPassword,
            }),
        });

        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: { success: true },
            error: null,
        };
    } catch (err: any) {
        return {
            data: null,
            error: {
                general: err?.message || 'Network error',
            },
        };
    }
};
