import { createModulePlugin } from '@/core/base/BaseModulePlugin'
import PurchaseTicketDialog from './components/PurchaseTicketDialog.vue'
import { EventsApiService, type EventsApiConfig } from './services/events-api'
import { useEvents, EVENTS_API_TOKEN } from './composables/useEvents'

export interface EventsModuleConfig {
  apiConfig: EventsApiConfig
  ticketValidationEndpoint?: string
  maxTicketsPerUser?: number
}

/**
 * Events Module Plugin
 * Provides event management and ticket purchasing functionality
 */
export const eventsModule = createModulePlugin({
  name: 'events',
  version: '1.0.0',
  dependencies: ['base'],
  
  components: {
    PurchaseTicketDialog
  },
  
  routes: [
    {
      path: '/events',
      name: 'events',
      component: () => import('./views/EventsPage.vue'),
      meta: {
        title: 'Events',
        requiresAuth: true
      }
    },
    {
      path: '/my-tickets',
      name: 'my-tickets',
      component: () => import('./views/MyTicketsPage.vue'),
      meta: {
        title: 'My Tickets',
        requiresAuth: true
      }
    }
  ],
  
  eventListeners: [
    {
      event: 'payment:completed',
      handler: (event) => {
        console.log('Events module: payment completed', event.data)
        // Could refresh events or ticket status here
      },
      description: 'Handle payment completion to refresh ticket status'
    },
    {
      event: 'events:ticket-purchased',
      handler: (event) => {
        console.log('Ticket purchased:', event.data)
        // Other modules can listen to this event
      },
      description: 'Emit ticket purchase events for other modules'
    }
  ],
  
  onInstall: async (_app, options) => {
    const config = options?.config as EventsModuleConfig | undefined
    if (!config) {
      throw new Error('Events module requires configuration')
    }

    // Create and register events API service manually since it needs config
    const eventsApiService = new EventsApiService(config.apiConfig)
    const { container } = await import('@/core/di-container')
    container.provide(EVENTS_API_TOKEN, eventsApiService)
  },
  
  onUninstall: async () => {
    const { container } = await import('@/core/di-container')
    container.remove(EVENTS_API_TOKEN)
  },
  
  exports: {
    composables: {
      useEvents
    }
  }
})

// Override auth logout handler for events-specific cleanup
;(eventsModule as any).handleAuthLogout = () => {
  console.log('Events module: user logged out, clearing cache')
  // Clear any cached event data if needed
}

export default eventsModule

// Re-export types and composables for external use
export type { Event, Ticket } from './types/event'
export { useEvents } from './composables/useEvents'