/** Pinia store for schedule management */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { BusSchedule } from '@/types'
import { schedulesService } from '@/services/schedulesService'

export const useScheduleStore = defineStore('schedule', () => {
    const schedules = ref<BusSchedule[]>([])
    const isLoading = ref(false)
    const error = ref<string | null>(null)

    // Safety: nunca más de 12s cargando (protección contra thread congelado por OS al apagar pantalla)
    let _safetyTimer: ReturnType<typeof setTimeout> | null = null
    function _startSafetyTimer() {
        _clearSafetyTimer()
        _safetyTimer = setTimeout(() => {
            if (isLoading.value) {
                console.warn('SIB | scheduleStore: safety timeout — reseteando isLoading')
                isLoading.value = false
            }
        }, 12000)
    }
    function _clearSafetyTimer() {
        if (_safetyTimer) { clearTimeout(_safetyTimer); _safetyTimer = null }
    }

    async function loadRouteSchedules(routeId: string, isBackground = false) {
        if (!isBackground) isLoading.value = true
        error.value = null
        if (!isBackground) _startSafetyTimer()
        try {
            schedules.value = await schedulesService.getRouteSchedules(routeId)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load schedules'
            console.error('Error loading schedules:', e)
        } finally {
            if (!isBackground) _clearSafetyTimer()
            if (!isBackground) isLoading.value = false
        }
    }

    async function loadStopSchedules(stopId: string, isBackground = false) {
        if (!isBackground) isLoading.value = true
        error.value = null
        if (!isBackground) _startSafetyTimer()
        try {
            schedules.value = await schedulesService.getStopSchedules(stopId)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load schedules'
            console.error('Error loading schedules:', e)
        } finally {
            if (!isBackground) _clearSafetyTimer()
            if (!isBackground) isLoading.value = false
        }
    }

    return {
        schedules,
        isLoading,
        error,
        loadRouteSchedules,
        loadStopSchedules,
    }
})

