import "server-only";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { COMMUNITY_WORKSPACE_LIMIT } from "@/lib/constants";
import { getOrganization } from "@/lib/organization/service";
import { CLOUD_STRIPE_FEATURE_LOOKUP_KEYS } from "@/modules/billing/lib/stripe-catalog";
import { getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
import type { TEntitlementFeature, TOrganizationEntitlementsContext } from "./types";

const mapLicenseFeaturesToEntitlements = (
  features: TOrganizationEntitlementsContext["licenseFeatures"]
): TEntitlementFeature[] => {
  if (!features) return [];

  const entitlementKeys: TEntitlementFeature[] = [];

  if (features.removeBranding || features.whitelabel) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.HIDE_BRANDING);
  }
  if (features.accessControl) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.RBAC);
  }
  if (features.quotas) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.QUOTA_MANAGEMENT);
  }
  if (features.spamProtection) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.SPAM_PROTECTION);
  }
  if (features.contacts) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.CONTACTS);
  }
  if (features.aiSmartTools) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.AI_SMART_TOOLS);
  }
  if (features.feedbackDirectories) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.FEEDBACK_DIRECTORIES);
  }
  if (features.dashboards) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.DASHBOARDS);
  }
  if (features.workflows) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.WORKFLOWS);
  }
  if (features.dataRetention) {
    entitlementKeys.push(CLOUD_STRIPE_FEATURE_LOOKUP_KEYS.DATA_RETENTION);
  }

  return entitlementKeys;
};

export const getSelfHostedOrganizationEntitlementsContext = async (
  organizationId: string
): Promise<TOrganizationEntitlementsContext> => {
  const [organization, license] = await Promise.all([
    getOrganization(organizationId),
    getEnterpriseLicense(),
  ]);

  if (!organization) {
    throw new ResourceNotFoundError("Organization", organizationId);
  }

  return {
    organizationId,
    source: "self_hosted_license",
    features: license.active ? mapLicenseFeaturesToEntitlements(license.features) : [],
    limits: {
      // null = unlimited; only an inactive or feature-less license falls back to the community default.
      workspaces:
        license.active && license.features ? license.features.workspaces : COMMUNITY_WORKSPACE_LIMIT,
      // Self-hosted response limits are not license-server-managed today.
      monthlyResponses: null,
      // Self-hosted workflows are gated by the boolean license feature, not metered (ENG-1936).
      monthlyWorkflowRuns: null,
    },
    licenseActive: license.active,
    licenseStatus: license.status,
    licenseFeatures: license.features,
    stripeCustomerId: null,
    subscriptionStatus: null,
    usageCycleAnchor: null,
  };
};
