/** Pinia store for bus stop management */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { BusStop } from '@/types'
import { busStopsService } from '@/services/busStopsService'

export const useBusStopStore = defineStore('busStop', () => {
    const selectedStop = ref<BusStop | null>(null)
    const busStops = ref<BusStop[]>([])
    const isLoading = ref(false)
    const error = ref<string | null>(null)
    const lastFetched = ref<number>(0)

    async function loadBusStops(force = false) {
        const CACHE_TIME = 1000 * 60 * 30; // 30 minutos
        const now = Date.now();

        if (isLoading.value) return;
        if (!force && busStops.value.length > 0 && (now - lastFetched.value < CACHE_TIME)) {
            return
        }

        isLoading.value = true
        error.value = null
        try {
            busStops.value = await busStopsService.getAllBusStops()
            lastFetched.value = now;
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load bus stops'
            console.error('Error loading bus stops:', e)
        } finally {
            isLoading.value = false
        }
    }

    async function loadBusStopById(id: string, force = false) {
        if (isLoading.value) return;
        // Buscar en cache primero
        if (!force && busStops.value.length > 0) {
            const cachedStop = busStops.value.find(s => s.id === id);
            if (cachedStop) {
                selectedStop.value = cachedStop;
                return;
            }
        }

        isLoading.value = true
        error.value = null
        try {
            selectedStop.value = await busStopsService.getBusStopById(id)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load bus stop'
            console.error('Error loading bus stop:', e)
        } finally {
            isLoading.value = false
        }
    }

    function setSelectedStop(stop: BusStop | null) {
        selectedStop.value = stop
    }

    return {
        selectedStop,
        busStops,
        isLoading,
        error,
        loadBusStops,
        loadBusStopById,
        setSelectedStop,
    }
})

