import { useMetadataStore } from '~/stores/metadata'
import { createTableDataStore } from '~/stores/tableDataFactory'

export default defineNuxtPlugin(async (nuxtApp) => {
  console.log('[TableStoresPlugin] Initializing...')

  // Wait for metadata to be available
  const metadataStore = useMetadataStore()

  // Initialize metadata first
  await metadataStore.initialize()
  console.log(`[TableStoresPlugin] Metadata initialized, found ${metadataStore.allTables.length} tables`)

  // Create stores for all available tables and preload from cache
  const tableStores = new Map<string, ReturnType<typeof createTableDataStore>>()
  const storeInstances = new Map<string, ReturnType<ReturnType<typeof createTableDataStore>>>()

  // Load all caches in parallel for better performance
  const cacheLoadPromises = metadataStore.allTables.map(async (metadata) => {
    const datasourceName = metadata.name // Use datasource name, not table name
    console.log(`[TableStoresPlugin] Creating store for datasource: ${datasourceName}`)

    const storeFactory = createTableDataStore(datasourceName, 100)
    const storeInstance = storeFactory()

    // Register both factory and instance
    tableStores.set(datasourceName, storeFactory)
    storeInstances.set(datasourceName, storeInstance)

    // Load from cache immediately
    await storeInstance.loadFromCache()
    console.log(`[TableStoresPlugin] Loaded ${storeInstance.recordCount} records for ${datasourceName}`)
  })

  // Wait for all caches to load
  await Promise.all(cacheLoadPromises)
  console.log('[TableStoresPlugin] All caches loaded successfully')

  // Provide access to table stores
  return {
    provide: {
      tableStores,
      // Helper function to get a table store (returns existing instance)
      getTableStore: (tableName: string) => {
        // First try to get existing instance
        const existingInstance = storeInstances.get(tableName)
        if (existingInstance) {
          return existingInstance
        }

        // Fall back to creating new instance from factory
        const storeFactory = tableStores.get(tableName)
        if (!storeFactory) {
          console.warn(`[TableStoresPlugin] Table store for "${tableName}" not found`)
          return null
        }

        const newInstance = storeFactory()
        storeInstances.set(tableName, newInstance)
        return newInstance
      }
    }
  }
})