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

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

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

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

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

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