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

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

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

export async function createPersona(data) {
    const res = await fetch(`${base}/personas/`, {
        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 updatePersona({ rut: id = null,  ...data }) {
    const res = await fetch(`${base}/personas/${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()
}