import { json } from '@sveltejs/kit';


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

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

    if (!id) return null;
	const data = await tryFetch(id)
	return json(data)
}


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

async function tryFetch(id, intentos = 0) {
    try {
        const token = await getToken() // token de autorizacion
        const data = await fetchParadero(id, token) // data de dispositivo
        return data;
    } catch (error) {
        if (intentos < 3) {
			console.log('Reintento', intentos + 1)
            await sleep(2); // espera 2 segundos
            return await tryFetch(id, intentos + 1)
        }
        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()
        return token;
    } catch (error) {
        console.log('token',{ error })
		throw 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 })
		throw error;
    }
}