
const {
    VITE_TRANSPORTE_API: base,
    VITE_TRANSPORTE_USER: user,
    VITE_TRANSPORTE_PASS: password
} = import.meta.env;

let intentos = 0;

export async function load({ url }) {
    const id = url.searchParams.get('id');

    if (!id) return null;
    return await tryFetch(id)
}

function sleep(seconds) {
    return new Promise((resolve) => {
        setTimeout(() => { resolve() }, seconds * 1000)
    })
}

async function tryFetch(id) {
    try {
        const token = await getToken() // token de autorizacion
        const data = await fetchParadero(id, token) // data de dispositivo
        intentos = 0;
        return data;
    } catch (error) {
        if (intentos < 3) {
            intentos++;
            await sleep(2); // espera 2 segundos
            return await tryFetch(id)
        }
        return null;
    }
}

async function getToken() {
    try {
        const res = await fetch(`${base}/auth/`, {
            method: 'POST',
            body: JSON.stringify({ rut: user, password })
        })
        if (!res.ok) throw await res.text()

        const { token } = await res.json()

        // console.log({ base })
        return token;
    } catch (error) {
        console.log('token',{ error })
    }
}

async function fetchParadero(id, token) {
    try {
        const data = {
            GetInfoDevice: {
                idDispositivo: id,
                KeyAuthorizacion: "token"
            }
        }

        const res = await fetch(`${base}/dispositivos/getInfoDevice/`, {
            method: 'POST',
            body: JSON.stringify(data),
            headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" }
        })

        if (!res.ok) throw await res.text()
        return res.json()

    } catch (error) {
        console.log('paradero',{ error })
    }
}