
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 form = new FormData()
    for (const key in data) {
        if (data[key]?.files?.length) {
            form.append(key, data[key].files[0], data[key].files[0].name)
        } else {
            form.append(key, data[key] || '')
        }
    }

    const res = await fetch(`${base}/personas/`, {
        method: 'POST',
        body: form,
        headers: { "Authorization": `Bearer ${getToken()}` }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function updatePersona({ rut: id = null,  ...data }) {
    console.log({ data })
    const form = new FormData()
    for (const key in data) {
        if (data[key]?.files?.length) {
            form.append(key, data[key].files[0], data[key].files[0].name)
        } else {
            form.append(key, data[key] || '')
        }
    }

    const res = await fetch(`${base}/personas/${id}/`, {
        method: 'PATCH',
        body: form,
        headers: { "Authorization": `Bearer ${getToken()}` }
    })
    if (!res.ok) throw await res.text()
    return res.json()
}

export async function getPhoto(id) {
    const res = await fetch(`${base}/personas/photo/?id=${id}`, {
        headers: { "Authorization": `Bearer ${getToken()}` }
    })
    if (!res.ok) throw await res.text()

    const blob = await res.blob()
    return URL.createObjectURL(blob);
}