/**
 * BreakPilot Compliance SDK - Vue 3 Plugin
 *
 * Usage:
 * import { createApp } from 'vue'
 * import { CompliancePlugin } from '@breakpilot/compliance-sdk-vue'
 *
 * const app = createApp(App)
 * app.use(CompliancePlugin, {
 *   apiEndpoint: 'https://compliance.example.com/api/v1',
 *   apiKey: 'pk_live_xxx',
 *   tenantId: 'tenant_xxx'
 * })
 */

import { type App, reactive, inject, type InjectionKey, readonly } from 'vue'
import {
  ComplianceClient,
  sdkReducer,
  DSGVOModule,
  ComplianceModule,
  RAGModule,
  SecurityModule,
  StateSyncManager,
} from '@breakpilot/compliance-sdk-core'
import type { SDKState, SDKAction } from '@breakpilot/compliance-sdk-types'
import { createInitialState } from '@breakpilot/compliance-sdk-types'

// ============================================================================
// Types
// ============================================================================

export interface CompliancePluginOptions {
  apiEndpoint: string
  apiKey: string
  tenantId?: string
  autoSync?: boolean
  syncInterval?: number
  debug?: boolean
}

export interface ComplianceStore {
  state: SDKState
  dispatch: (action: SDKAction) => void
  client: ComplianceClient
  dsgvo: DSGVOModule
  compliance: ComplianceModule
  rag: RAGModule
  security: SecurityModule
  syncManager: StateSyncManager
  isReady: boolean
  error: Error | null
}

// ============================================================================
// Injection Key
// ============================================================================

export const COMPLIANCE_KEY: InjectionKey<ComplianceStore> = Symbol('compliance')

// ============================================================================
// Plugin
// ============================================================================

export const CompliancePlugin = {
  install(app: App, options: CompliancePluginOptions): void {
    // Create client
    const client = new ComplianceClient({
      apiEndpoint: options.apiEndpoint,
      apiKey: options.apiKey,
      tenantId: options.tenantId,
    })

    // Create reactive state
    const state = reactive<SDKState>(createInitialState())

    // Create dispatch function
    const dispatch = (action: SDKAction): void => {
      const newState = sdkReducer(state, action)
      Object.assign(state, newState)
    }

    // Create modules
    const dsgvo = new DSGVOModule(state, dispatch, client)
    const compliance = new ComplianceModule(state, dispatch, client)
    const rag = new RAGModule(state, dispatch, client)
    const security = new SecurityModule(state, dispatch, client)

    // Create sync manager
    const syncManager = new StateSyncManager({
      client,
      syncInterval: options.syncInterval || 30000,
      onStateLoaded: loadedState => {
        Object.assign(state, loadedState)
      },
      onSyncError: error => {
        console.error('[ComplianceSDK] Sync error:', error)
        store.error = error
      },
    })

    // Create store
    const store = reactive<ComplianceStore>({
      state: state as SDKState,
      dispatch,
      client,
      dsgvo,
      compliance,
      rag,
      security,
      syncManager,
      isReady: false,
      error: null,
    })

    // Initialize
    const initialize = async (): Promise<void> => {
      try {
        // Load state from server
        const savedState = await client.getState()
        if (savedState) {
          Object.assign(state, savedState.state)
        }

        // Start sync if enabled
        if (options.autoSync !== false) {
          syncManager.start()
        }

        store.isReady = true

        if (options.debug) {
          console.log('[ComplianceSDK] Initialized:', state)
        }
      } catch (error) {
        store.error = error instanceof Error ? error : new Error(String(error))
        console.error('[ComplianceSDK] Initialization failed:', error)
      }
    }

    // Start initialization
    initialize()

    // Provide store
    app.provide(COMPLIANCE_KEY, store)

    // Also make available as global property
    app.config.globalProperties.$compliance = store
  },
}

// ============================================================================
// Injection Helper
// ============================================================================

export function useComplianceStore(): ComplianceStore {
  const store = inject(COMPLIANCE_KEY)
  if (!store) {
    throw new Error(
      '[ComplianceSDK] No store found. Did you forget to install the CompliancePlugin?'
    )
  }
  return store
}
