import { captureException } from '@sentry/browser';
import { type FirebaseApp, initializeApp } from 'firebase/app';
import { getMessaging, isSupported, type Messaging } from 'firebase/messaging';
import { experimentalSetDeliveryMetricsExportedToBigQueryEnabled } from 'firebase/messaging/sw';
import { type FirebasePerformance, getPerformance } from 'firebase/performance';
import { getRemoteConfig, type RemoteConfig } from 'firebase/remote-config';

const firebaseConfig = {
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
  storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_FIREBASE_APP_ID,
  measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID,
};

export let app: FirebaseApp | undefined;
export let messaging: Messaging | undefined;
export let perf: FirebasePerformance | undefined;
export let remoteConfig: RemoteConfig | undefined;

export const isScopedFeatureConfig = (
  value: unknown,
): value is ScopedFeatureConfig => {
  return (
    typeof value === 'object' &&
    value !== null &&
    'instances' in value &&
    Array.isArray(value.instances)
  );
};

export type ScopedFeatureConfig = {
  instances: number[];
};

const defaultScopedFeatureConfig: ScopedFeatureConfig = {
  instances: [],
};

type DocumentsTabExternalUrl = {
  instanceId: number;
  urls: string[];
};

const defaultDocumentsTabExternalUrls: DocumentsTabExternalUrl[] = [];

export const FEATURE_FLAG_KEYS = {
  DOCUMENTS_TAB_EXTERNAL_URLS: 'DOCUMENTS_TAB_EXTERNAL_URLS',
  ENABLE_EMPLOYEE_LIFECYCLE: 'ENABLE_EMPLOYEE_LIFECYCLE',
  ENABLE_WEB_EXPERIMENTAL_RESULTS: 'ENABLE_WEB_EXPERIMENTAL_RESULTS',
  SPORTS_POOL_ENABLED: 'SPORTS_POOL_ENABLED',
  VIEW_KNOWLEDGE_LIBRARIES_V2: 'VIEW_KNOWLEDGE_LIBRARIES_V2',

  // TEST_EXAMPLE_STRING: 'TEST_EXAMPLE_STRING',
  // TEST_EXAMPLE_NUMBER: 'TEST_EXAMPLE_NUMBER',
  // TEST_EXAMPLE_OBJECT: 'TEST_EXAMPLE_OBJECT',
  // TEST_EXAMPLE_ARRAY: 'TEST_EXAMPLE_ARRAY',
} as const;

// --- Default Values ---
// These are used immediately on startup, before fetching,
// and if fetching fails or is unavailable.
export const defaultConfig = {
  [FEATURE_FLAG_KEYS.DOCUMENTS_TAB_EXTERNAL_URLS]:
    defaultDocumentsTabExternalUrls,
  [FEATURE_FLAG_KEYS.ENABLE_EMPLOYEE_LIFECYCLE]: false,
  [FEATURE_FLAG_KEYS.ENABLE_WEB_EXPERIMENTAL_RESULTS]:
    defaultScopedFeatureConfig,
  [FEATURE_FLAG_KEYS.SPORTS_POOL_ENABLED]: false,
  [FEATURE_FLAG_KEYS.VIEW_KNOWLEDGE_LIBRARIES_V2]: false,
  // [FEATURE_FLAG_KEYS.TEST_EXAMPLE_STRING]: 'default string',
  // [FEATURE_FLAG_KEYS.TEST_EXAMPLE_NUMBER]: 123,
  // [FEATURE_FLAG_KEYS.TEST_EXAMPLE_OBJECT]: {
  //   instances: [],
  // } as { instances: string[] },
  // [FEATURE_FLAG_KEYS.TEST_EXAMPLE_ARRAY]: [] as string[],
};

// Keys are defined in FEATURE_FLAG_KEYS
export type FeatureFlagKey =
  (typeof FEATURE_FLAG_KEYS)[keyof typeof FEATURE_FLAG_KEYS];
// Values are inferred from defaultConfig
export type FeatureFlagValues = typeof defaultConfig;

try {
  app = initializeApp(firebaseConfig);
  perf = getPerformance(app);
  remoteConfig = getRemoteConfig(app);

  // 10 seconds (development) vs 12 hours (production)
  remoteConfig.settings.minimumFetchIntervalMillis =
    import.meta.env.NODE_ENV === 'production'
      ? 43200000 // 12 hours in production (12 * 60 * 60 * 1000)
      : 10000; // 10 seconds in development

  // @ts-expect-error
  remoteConfig.defaultConfig = defaultConfig;

  isSupported().then(supported => {
    if (supported) {
      messaging = getMessaging(app);
      experimentalSetDeliveryMetricsExportedToBigQueryEnabled(messaging, true);
    }
  });
} catch (error) {
  captureException(error);
}

export default app;
