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

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

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

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