/**
 * Vue plugin for global installation.
 *
 * Phase 4: extracted from vue/index.ts.
 */

import { computed, ref, type Ref } from 'vue';
import { ConsentManager } from '../core/ConsentManager';
import type {
  ConsentCategories,
  ConsentCategory,
  ConsentConfig,
  ConsentState,
} from '../types';
import { CONSENT_KEY, type ConsentContext } from './context';

/**
 * Vue Plugin fuer globale Installation.
 *
 * @example
 * ```ts
 * app.use(ConsentPlugin, { apiEndpoint: '...', siteId: '...' });
 * ```
 */
export const ConsentPlugin = {
  install(
    app: { provide: (key: symbol | string, value: unknown) => void },
    config: ConsentConfig
  ) {
    const manager = new ConsentManager(config);
    const consent = ref<ConsentState | null>(null);
    const isInitialized = ref(false);
    const isLoading = ref(true);
    const isBannerVisible = ref(false);

    manager.init().then(() => {
      consent.value = manager.getConsent();
      isInitialized.value = true;
      isLoading.value = false;
      isBannerVisible.value = manager.isBannerVisible();
    });

    manager.on('change', (newConsent) => {
      consent.value = newConsent;
    });
    manager.on('banner_show', () => {
      isBannerVisible.value = true;
    });
    manager.on('banner_hide', () => {
      isBannerVisible.value = false;
    });

    const context: ConsentContext = {
      manager: ref(manager) as Ref<ConsentManager | null>,
      consent: consent as Ref<ConsentState | null>,
      isInitialized,
      isLoading,
      isBannerVisible,
      needsConsent: computed(() => manager.needsConsent()),
      hasConsent: (category: ConsentCategory) => manager.hasConsent(category),
      acceptAll: () => manager.acceptAll(),
      rejectAll: () => manager.rejectAll(),
      saveSelection: async (categories: Partial<ConsentCategories>) => {
        await manager.setConsent(categories);
        manager.hideBanner();
      },
      showBanner: () => manager.showBanner(),
      hideBanner: () => manager.hideBanner(),
      showSettings: () => manager.showSettings(),
    };

    app.provide(CONSENT_KEY, context);
  },
};
