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

export async function getRolesyaplicaciones(idRol) {
    const params = idRol ? { id_rol: idRol } : null;  // Preparar los parámetros de la consulta    
    const query = params ? '?' + new URLSearchParams(params).toString() : '';    
    const res = await fetch(`${base}/rolyaplicacion/${query}`, {
        headers: {"Authorization": `Bearer ${getToken()}`,"Content-Type": "application/json"}
    });   
    if (!res.ok) throw await res.json();   
    return res.json();
}

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


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

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