import { DEFAULT_LICENSE_RESOLUTION } from './license.defaults';
import { getEnabledLicenseFeatures } from './license.catalog';
import { getCommercialQuotaState, type AsukaCommercialQuotaKey } from './commercial-limits';
import { canUseFeature, hasPlan, isLicenseUsable, isLicenseWithinGrace } from './feature-gates';
import type { AsukaLicenseFeature, AsukaLicensePlan, AsukaLicenseResolutionResult } from './license.types';

let currentResolution: AsukaLicenseResolutionResult = DEFAULT_LICENSE_RESOLUTION;

export function setCurrentLicenseResolution(resolution: AsukaLicenseResolutionResult | null | undefined): void {
  currentResolution = resolution ?? DEFAULT_LICENSE_RESOLUTION;
}

export function getCurrentLicenseResolution(): AsukaLicenseResolutionResult {
  return currentResolution;
}

export function getCurrentLicenseEntitlements() {
  return currentResolution.payload;
}

export function isCurrentLicenseUsable(): boolean {
  return isLicenseUsable(currentResolution.payload);
}

export function isCurrentLicenseWithinGrace(): boolean {
  return isLicenseWithinGrace(currentResolution.payload);
}

export function getCurrentLicenseEnabledFeatures(): string[] {
  return getEnabledLicenseFeatures(currentResolution.payload);
}

export function getCurrentLicenseLimits() {
  return currentResolution.payload?.limits ?? {};
}

export function getCurrentLicenseUsage() {
  return currentResolution.payload?.usage ?? {};
}

export function getCurrentLicenseQuota(key: AsukaCommercialQuotaKey) {
  return getCommercialQuotaState(currentResolution.payload, key);
}

export function canUseLicenseFeature(feature: AsukaLicenseFeature | string): boolean {
  return canUseFeature(currentResolution.payload, feature);
}

export function currentLicenseHasPlan(plan: Extract<AsukaLicensePlan, 'starter' | 'pro' | 'agency'>): boolean {
  return hasPlan(currentResolution.payload, plan);
}
