import { computed } from 'vue'
import { useAsyncState } from '@vueuse/core'
import { injectService } from '@/core/di-container'
import type { Event } from '../types/event'
import type { EventsApiService } from '../services/events-api'

// Service token for events API
export const EVENTS_API_TOKEN = Symbol('eventsApi')

export function useEvents() {
  const eventsApi = injectService<EventsApiService>(EVENTS_API_TOKEN)
  
  if (!eventsApi) {
    throw new Error('EventsApiService not available. Make sure events module is installed.')
  }

  const { state: events, isLoading, error: asyncError, execute: refresh } = useAsyncState(
    () => eventsApi.fetchEvents(),
    [] as Event[],
    {
      immediate: true,
      resetOnExecute: false,
    }
  )

  const error = computed(() => {
    if (asyncError.value) {
      return {
        message: asyncError.value instanceof Error
          ? asyncError.value.message
          : 'An error occurred while fetching events'
      }
    }
    return null
  })

  const sortedEvents = computed(() => {
    return [...events.value].sort((a, b) =>
      new Date(b.time).getTime() - new Date(a.time).getTime()
    )
  })

  const upcomingEvents = computed(() => {
    const now = new Date()
    return sortedEvents.value.filter(event =>
      new Date(event.event_start_date) > now
    )
  })

  const pastEvents = computed(() => {
    const now = new Date()
    return sortedEvents.value.filter(event =>
      new Date(event.event_end_date) < now
    )
  })

  return {
    events: sortedEvents,
    upcomingEvents,
    pastEvents,
    isLoading,
    error,
    refresh,
  }
} 
