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

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

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

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

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

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