
import { base, getToken } from './_config'

export async function getUsuarios(params) {
    const query = !params ? '' : '?' + (new URLSearchParams(params).toString());
    const res = await fetch(`${base}/usuarios/${query}`, {
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function getUsuario(id) {
    const res = await fetch(`${base}/usuarios/${id}/`, {
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function getPermisosApp() {
    const res = await fetch(`${base}/usuarios/permisos/`, {
        method: 'POST',
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function createUsuario(data) {
    const res = await fetch(`${base}/usuarios/`, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function updateUsuario({ login: id = null, ...data }) {
    const res = await fetch(`${base}/usuarios/${id}/`, {
        method: 'PATCH',
        body: JSON.stringify(data),
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function deleteUsuario(id) {
    const res = await fetch(`${base}/usuarios/${id}/`, {
        method: 'DELETE',
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.text()
}