import { canUseFeature } from './feature-gates';
import type { AsukaLicenseEntitlements } from './license.types';
import { getCurrentLicenseEntitlements } from './runtime';

const PREMIUM_RUNTIME_FEATURES = [
  'studioBasic',
  'pricing',
  'pexels',
  'pixabay',
  'facebookImages',
  'advancedPricing',
  'pricingRules',
  'drawingAreas',
  'fixedSlots',
  'modelOptimization',
  'assembly',
  'productParameters',
  'apiAdvanced',
  'backgroundRemoval',
] as const;

let premiumRuntimeModulePromise: Promise<typeof import('../../premium/registerPremiumRuntime')> | null = null;

export function shouldLoadPremiumRuntime(license: AsukaLicenseEntitlements | null | undefined): boolean {
  return PREMIUM_RUNTIME_FEATURES.some((feature) => canUseFeature(license, feature));
}

export async function ensurePremiumRuntimeLoaded(
  license: AsukaLicenseEntitlements | null | undefined = getCurrentLicenseEntitlements(),
): Promise<void> {
  if (!premiumRuntimeModulePromise) {
    premiumRuntimeModulePromise = import('../../premium/registerPremiumRuntime')
      .catch((error) => {
        premiumRuntimeModulePromise = null;
        throw error;
      });
  }
  const premiumRuntime = await premiumRuntimeModulePromise;
  await premiumRuntime.registerPremiumRuntime(license);
}
