import AuthService from '@/service/AuthService';

const { API_URL, authFetch, readErrorMessage } = AuthService;

async function createUser(email, password) {
    const res = await authFetch(`${API_URL}/api/admin/users`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
    });
    if (!res.ok) throw new Error(await readErrorMessage(res));
}

async function assignRoles(email, roles) {
    const res = await authFetch(`${API_URL}/api/admin/users/roles`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, roles })
    });
    if (!res.ok) throw new Error(await readErrorMessage(res));
}

async function getRoles() {
    const res = await authFetch(`${API_URL}/api/admin/roles`, { method: 'GET' });
    if (!res.ok) throw new Error(await readErrorMessage(res));
    return res.json();
}

async function listUsers(page = 0, size = 20) {
    const res = await authFetch(`${API_URL}/api/admin/users?page=${page}&size=${size}`, { method: 'GET' });
    if (!res.ok) throw new Error(await readErrorMessage(res));
    return res.json();
}

async function updateUser(payload) {
    const res = await authFetch(`${API_URL}/api/admin/users/update`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    });
    if (!res.ok) throw new Error(await readErrorMessage(res));
}

async function deleteUser(id) {
    const res = await authFetch(`${API_URL}/api/admin/users?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
    if (!res.ok) throw new Error(await readErrorMessage(res));
}

export default { createUser, assignRoles, getRoles, listUsers, updateUser, deleteUser };
