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

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

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

export async function createOperador(data) {
    const res = await fetch(`${base}/operadores/`, {
        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 updateOperador({ id_operador: id = null,  ...data }) {
    const res = await fetch(`${base}/operadores/${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 deleteOperador(id) {
    const res = await fetch(`${base}/operadores/${id}/`, {
        method: 'DELETE',
        headers: { "Authorization": `Bearer ${getToken()}`, "Content-Type": "application/json" }
    })
    if (!res.ok) throw await res.text()
    return res.text()
}
