import { supabase } from '@/supabase';

export const schedulesService = {
    async getRouteSchedules(routeId: string, onlyPublished = true) {
        let query = supabase.from('bus_schedules')
            .select('*')
            .eq('route_id', routeId)
            .order('departure_time', { ascending: true })

        if (onlyPublished) query = query.eq('is_published', true)
        const { data, error } = await query
        if (error) throw new Error(error.message)
        return data
    },

    async getStopSchedules(stopId: string, onlyPublished = true) {
        // Get routes passing through this stop, then get their schedules
        const { data: routeStops, error: rsError } = await supabase
            .from('route_stops').select('route_id').eq('stop_id', stopId)
        if (rsError) throw new Error(rsError.message)

        const routeIds = (routeStops || []).map((rs: any) => rs.route_id)
        if (routeIds.length === 0) return []

        let query = supabase.from('bus_schedules')
            .select('*')
            .in('route_id', routeIds)
            .order('departure_time', { ascending: true })

        if (onlyPublished) query = query.eq('is_published', true)
        const { data, error } = await query
        if (error) throw new Error(error.message)
        return data
    },

    async createSchedule(scheduleData: any) {
        const { data, error } = await supabase.from('bus_schedules').insert([scheduleData]).select().single()
        if (error) throw new Error(error.message)
        return data
    },

    async updateSchedule(scheduleId: string, updateData: any) {
        const { data, error } = await supabase.from('bus_schedules').update(updateData).eq('id', scheduleId).select().single()
        if (error) throw new Error(error.message)
        return data
    },

    async deleteSchedule(scheduleId: string) {
        const { error } = await supabase.from('bus_schedules').delete().eq('id', scheduleId)
        if (error) throw new Error(error.message)
    }
};
