import type { AsukaLicenseEntitlements, AsukaLicenseFeature, AsukaLicenseFeatureDefinition, AsukaLicenseLimits, AsukaLicensePlan } from './license.types';

export type PlanCatalogEntry = {
  key: AsukaLicensePlan;
  label: string;
  description: string;
  priceHint?: string;
  stripePriceId?: string;
  features: ReadonlyArray<AsukaLicenseFeature>;
  limits: AsukaLicenseLimits;
};

export const ASUKA_LICENSE_FEATURE_CATALOG: ReadonlyArray<AsukaLicenseFeatureDefinition> = [
  {
    key: 'basicEditor',
    label: 'Core editor',
    description: 'Enable the base product designer runtime.',
    tier: 'starter',
    category: 'core',
  },
  {
    key: 'views',
    label: 'Views',
    description: 'Create and switch product views such as front/back layouts.',
    tier: 'starter',
    category: 'core',
  },
  {
    key: 'layers',
    label: 'Layers',
    description: 'Manage object ordering and layer visibility.',
    tier: 'starter',
    category: 'core',
  },
  {
    key: 'history',
    label: 'History',
    description: 'Undo, redo, and reset designer changes.',
    tier: 'starter',
    category: 'core',
  },
  {
    key: 'zoom',
    label: 'Zoom tools',
    description: 'Use zoom, magnifier, and ruler helpers.',
    tier: 'starter',
    category: 'core',
  },
  {
    key: 'text',
    label: 'Text editing',
    description: 'Add and edit text objects on the canvas.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'imageUpload',
    label: 'Image upload',
    description: 'Upload local image assets into the designer.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'qrcodeImages',
    label: 'QR code images',
    description: 'Generate QR code image elements.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'basicDesigns',
    label: 'Basic designs',
    description: 'Use the base design/catalog primitives.',
    tier: 'starter',
    category: 'asset',
  },
  {
    key: 'designCatalog',
    label: 'Design catalog',
    description: 'Expose a simple local design catalog for the designer.',
    tier: 'starter',
    category: 'asset',
  },
  {
    key: 'shapes',
    label: 'Shapes',
    description: 'Add reusable SVG shapes and simple graphic elements.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'colors',
    label: 'Colors',
    description: 'Manage product colors and print color choices.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'printingMethods',
    label: 'Printing methods',
    description: 'Expose print method choices and related constraints.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'studioBasic',
    label: 'Basic Studio',
    description: 'Use the standard Studio preview and simple adjustments.',
    tier: 'starter',
    category: 'module',
  },
  {
    key: 'pricing',
    label: 'Pricing summary',
    description: 'Display and format base pricing information.',
    tier: 'starter',
    category: 'pricing',
  },
  {
    key: 'pricingBasic',
    label: 'Basic pricing',
    description: 'Use simple price display and manual price metadata.',
    tier: 'starter',
    category: 'pricing',
  },
  {
    key: 'standardExport',
    label: 'Standard export',
    description: 'Export standard-resolution files from the designer.',
    tier: 'starter',
    category: 'export',
  },
  {
    key: 'aiCredits',
    label: 'AI credits',
    description: 'Enable the monthly AI credit quota used by AI-backed workflows.',
    tier: 'pro',
    category: 'runtime',
  },
  {
    key: 'studioAdvanced',
    label: 'Advanced Studio',
    description: 'Unlock advanced Studio tabs such as kernels and color-removal helpers.',
    tier: 'pro',
    category: 'module',
  },
  {
    key: 'pexels',
    label: 'Pexels provider',
    description: 'Enable the Pexels image provider in the Images module.',
    tier: 'starter',
    category: 'provider',
  },
  {
    key: 'pixabay',
    label: 'Pixabay provider',
    description: 'Enable the Pixabay image provider in the Images module.',
    tier: 'starter',
    category: 'provider',
  },
  {
    key: 'facebookImages',
    label: 'Facebook provider',
    description: 'Enable the Facebook image provider in the Images module.',
    tier: 'pro',
    category: 'provider',
  },
  {
    key: 'premiumTemplates',
    label: 'Premium templates',
    description: 'Unlock premium design/template catalogs.',
    tier: 'pro',
    category: 'asset',
  },
  {
    key: 'advancedPricing',
    label: 'Advanced pricing',
    description: 'Unlock advanced pricing automation.',
    tier: 'pro',
    category: 'pricing',
  },
  {
    key: 'pricingRules',
    label: 'Pricing rules',
    description: 'Unlock rule-based pricing conditions and computed add-ons.',
    tier: 'pro',
    category: 'pricing',
  },
  {
    key: 'hdExport',
    label: 'HD export',
    description: 'Unlock print-quality export presets above the base workflow.',
    tier: 'pro',
    category: 'export',
  },
  {
    key: 'serverHdExport',
    label: 'Server HD export',
    description: 'Render production-quality 2D and 3D exports on the protected Asuka server.',
    tier: 'pro',
    category: 'export',
  },
  {
    key: 'transparentExport',
    label: 'Transparent export',
    description: 'Export transparent PNG/WebP assets for production workflows.',
    tier: 'pro',
    category: 'export',
  },
  {
    key: 'batchExport',
    label: 'Batch export',
    description: 'Unlock multi-export workflows, including all views and drawing areas.',
    tier: 'pro',
    category: 'export',
  },
  {
    key: 'drawingAreas',
    label: 'Drawing areas',
    description: 'Unlock dedicated drawing-area management tools and overlays.',
    tier: 'pro',
    category: 'module',
  },
  {
    key: 'fixedSlots',
    label: 'Fixed slots',
    description: 'Unlock marker/fixed-slot authoring tools.',
    tier: 'pro',
    category: 'module',
  },
  {
    key: 'modelOptimization',
    label: 'GLB optimization',
    description: 'Optimize, merge, simplify, normalize, and prepare static GLB assets.',
    tier: 'pro',
    category: 'module',
  },
  {
    key: 'assembly',
    label: 'Spatial assembly',
    description: 'Build configurable 3D spaces with snapping, constraints, measurements, and production outputs.',
    tier: 'pro',
    category: 'module',
  },
  {
    key: 'productParameters',
    label: 'Product parameters',
    description: 'Expose live controls for configurable 3D dimensions and product parameters.',
    tier: 'pro',
    category: 'module',
  },
  {
    key: 'advancedPermissions',
    label: 'Advanced permissions',
    description: 'Unlock advanced permission and policy orchestration for multi-client setups.',
    tier: 'agency',
    category: 'team',
  },
  {
    key: 'whiteLabel',
    label: 'White label',
    description: 'Remove product branding and prepare Pro/Agency client deployments.',
    tier: 'pro',
    category: 'branding',
  },
  {
    key: 'apiAdvanced',
    label: 'Advanced API',
    description: 'Expose advanced runtime controls for integrations and automation.',
    tier: 'agency',
    category: 'api',
  },
  {
    key: 'backgroundRemoval',
    label: 'Background removal',
    description: 'Enable premium background-removal workflows backed by a remote service.',
    tier: 'agency',
    category: 'runtime',
  },
] as const;

export const ASUKA_PLAN_DEFAULT_FEATURES: Readonly<Record<AsukaLicensePlan, ReadonlyArray<AsukaLicenseFeature>>> = {
  free: [],
  starter: [
    'basicEditor',
    'views',
    'layers',
    'history',
    'zoom',
    'text',
    'imageUpload',
    'qrcodeImages',
    'basicDesigns',
    'designCatalog',
    'shapes',
    'colors',
    'printingMethods',
    'studioBasic',
    'pricing',
    'pricingBasic',
    'standardExport',
    'pexels',
    'pixabay',
  ],
  pro: [
    'basicEditor',
    'views',
    'layers',
    'history',
    'zoom',
    'text',
    'imageUpload',
    'qrcodeImages',
    'basicDesigns',
    'designCatalog',
    'shapes',
    'colors',
    'printingMethods',
    'studioBasic',
    'pricing',
    'pricingBasic',
    'standardExport',
    'aiCredits',
    'studioAdvanced',
    'pexels',
    'pixabay',
    'facebookImages',
    'premiumTemplates',
    'advancedPricing',
    'pricingRules',
    'hdExport',
    'serverHdExport',
    'transparentExport',
    'batchExport',
    'drawingAreas',
    'fixedSlots',
    'modelOptimization',
    'assembly',
    'productParameters',
    'whiteLabel',
  ],
  agency: [
    'basicEditor',
    'views',
    'layers',
    'history',
    'zoom',
    'text',
    'imageUpload',
    'qrcodeImages',
    'basicDesigns',
    'designCatalog',
    'shapes',
    'colors',
    'printingMethods',
    'studioBasic',
    'pricing',
    'pricingBasic',
    'standardExport',
    'aiCredits',
    'studioAdvanced',
    'pexels',
    'pixabay',
    'facebookImages',
    'premiumTemplates',
    'advancedPricing',
    'pricingRules',
    'hdExport',
    'serverHdExport',
    'transparentExport',
    'batchExport',
    'drawingAreas',
    'fixedSlots',
    'modelOptimization',
    'assembly',
    'productParameters',
    'advancedPermissions',
    'whiteLabel',
    'apiAdvanced',
    'backgroundRemoval',
  ],
} as const;

export const ASUKA_PLAN_DEFAULT_LIMITS: Readonly<Record<AsukaLicensePlan, AsukaLicenseLimits>> = {
  free: {},
  starter: {
    sites: 1,
    activations: 1,
    users: 1,
    exportsPerMonth: 25,

    viewsPerProduct: 2,
    objectsPerDesign: 25,
    savedDesigns: 10,
    printProfiles: 5,
    batchExportSize: 1,
  },
  pro: {
    sites: 3,
    activations: 3,
    users: 3,
    exportsPerMonth: 250,



    aiCreditsPerMonth: 500,
    viewsPerProduct: 6,
    objectsPerDesign: 100,
    savedDesigns: 100,
    printProfiles: 50,
    batchExportSize: 25,
  },
  agency: {
    sites: 25,
    activations: 25,
    users: 25,
    exportsPerMonth: 5000,



    aiCreditsPerMonth: 2500,
    viewsPerProduct: 0,
    objectsPerDesign: 0,
    savedDesigns: 0,
    printProfiles: 0,
    batchExportSize: 250,
  },
} as const;

export const ASUKA_LICENSE_PLAN_CATALOG: Readonly<Record<AsukaLicensePlan, PlanCatalogEntry>> = {
  free: {
    key: 'free',
    label: 'Free',
    description: 'No active commercial entitlement.',
    features: [],
    limits: ASUKA_PLAN_DEFAULT_LIMITS.free,
  },
  starter: {
    key: 'starter',
    label: 'Starter',
    description: 'A clean single-site designer for small stores and simple personalization flows.',
    priceHint: '29 EUR / month',
    stripePriceId: 'price_1TO3BF7Y4yPmC18RZ0ExNLC4',
    features: ASUKA_PLAN_DEFAULT_FEATURES.starter,
    limits: ASUKA_PLAN_DEFAULT_LIMITS.starter,
  },
  pro: {
    key: 'pro',
    label: 'Pro',
    description: 'The main commerce plan with providers, HD exports, templates, pricing rules, and advanced production tools.',
    priceHint: '39 EUR / month',
    stripePriceId: 'price_1TO3BX7Y4yPmC18RwfX0BIiy',
    features: ASUKA_PLAN_DEFAULT_FEATURES.pro,
    limits: ASUKA_PLAN_DEFAULT_LIMITS.pro,
  },
  agency: {
    key: 'agency',
    label: 'Agency',
    description: 'A multi-site agency plan for client deployments, shared assets, permissions, and high-volume workflows.',
    priceHint: '59 EUR / year',
    stripePriceId: 'price_1TO3Bo7Y4yPmC18R5GIM0n9S',
    features: ASUKA_PLAN_DEFAULT_FEATURES.agency,
    limits: ASUKA_PLAN_DEFAULT_LIMITS.agency,
  },
} as const;


export function getLicenseFeatureDefinition(feature: AsukaLicenseFeature | string): AsukaLicenseFeatureDefinition | undefined {
  const key = String(feature ?? '').trim();
  return ASUKA_LICENSE_FEATURE_CATALOG.find((entry) => entry.key === key);
}

export function getPlanDefaultFeatures(plan: AsukaLicensePlan | null | undefined): Partial<Record<AsukaLicenseFeature, boolean>> {
  const resolvedPlan = plan ?? 'free';
  const defaults = ASUKA_PLAN_DEFAULT_FEATURES[resolvedPlan] ?? [];
  return defaults.reduce((acc, key) => {
    acc[key] = true;
    return acc;
  }, {} as Partial<Record<AsukaLicenseFeature, boolean>>);
}

export function mergeLicenseFeaturesWithPlan(
  plan: AsukaLicensePlan | null | undefined,
  input: Partial<Record<AsukaLicenseFeature | string, boolean>> | null | undefined,
): Partial<Record<AsukaLicenseFeature | string, boolean>> {
  const merged: Partial<Record<AsukaLicenseFeature | string, boolean>> = {
    ...getPlanDefaultFeatures(plan),
  };

  Object.entries(input ?? {}).forEach(([key, enabled]) => {
    merged[key] = enabled;
  });

  return merged;
}

export function mergeLicenseLimitsWithPlan(
  plan: AsukaLicensePlan | null | undefined,
  input: AsukaLicenseLimits | null | undefined,
): AsukaLicenseLimits {
  return {
    ...(ASUKA_PLAN_DEFAULT_LIMITS[plan ?? 'free'] ?? {}),
    ...(input ?? {}),
  };
}

export function isLicenseFeatureEnabledInMap(
  features: Partial<Record<AsukaLicenseFeature | string, boolean>> | null | undefined,
  feature: AsukaLicenseFeature | string,
): boolean {
  const key = String(feature ?? '').trim();
  return features?.[key] === true;
}

export function getEnabledLicenseFeatures(
  entitlements: Pick<AsukaLicenseEntitlements, 'plan' | 'features'> | null | undefined,
): string[] {
  const merged = mergeLicenseFeaturesWithPlan(entitlements?.plan ?? 'free', entitlements?.features ?? {});
  return Object.entries(merged)
    .filter(([, enabled]) => enabled === true)
    .map(([key]) => key)
    .sort((a, b) => a.localeCompare(b));
}
