import "server-only";
import { cache as reactCache } from "react";
import Stripe from "stripe";
import { createCacheKey } from "@formbricks/cache";
import { logger } from "@formbricks/logger";
import type { TCloudBillingInterval } from "@formbricks/types/organizations";
import { cache } from "@/lib/cache";
import { env } from "@/lib/env";
import { hashString } from "@/lib/hash-string";
import { type TResponsePricingTier, mapStripeTiersToResponsePricingTiers } from "./response-pricing-tiers";
import { stripeClient } from "./stripe-client";

export type TStandardCloudPlan = "hobby" | "pro" | "scale";
type TStripePriceKind = "base" | "responses" | "workflow_runs";

type TStripeCatalogPrice = Stripe.Price & {
  product: Stripe.Product | Stripe.DeletedProduct;
};

export type TStripeBillingCatalogItem = {
  plan: TStandardCloudPlan;
  interval: TCloudBillingInterval;
  basePrice: TStripeCatalogPrice;
  responsePrice: TStripeCatalogPrice | null;
  // Metered workflow-run overage. Only present on plans that include workflows (Scale today); null
  // elsewhere. Like responsePrice it is always the monthly-billed metered variant, even for a yearly
  // base, because usage is aggregated and billed monthly (ENG-1936).
  workflowRunsPrice: TStripeCatalogPrice | null;
  // The included (free) workflow-run allowance DERIVED FROM the price's own free first tier — the
  // single source of truth the usage card renders. Null when there is no workflow price. This is
  // deliberately NOT the entitlement's included-<n> value: the number the UI shows and the number
  // Stripe leaves uncharged must be the same object, or the card can reassure a customer they are
  // inside an allowance while Stripe invoices them (ENG-2193/2194).
  workflowRunsIncluded: number | null;
};

export type TStripeBillingCatalog = {
  hobby: {
    monthly: TStripeBillingCatalogItem;
  };
  pro: {
    monthly: TStripeBillingCatalogItem;
    yearly: TStripeBillingCatalogItem;
  };
  scale: {
    monthly: TStripeBillingCatalogItem;
    yearly: TStripeBillingCatalogItem;
  };
};

export type TResponseOverageDisplay = {
  currency: string;
  tiers: TResponsePricingTier[];
};

export type TStripeBillingCatalogDisplayItem = {
  plan: TStandardCloudPlan;
  interval: TCloudBillingInterval;
  currency: string;
  unitAmount: number | null;
  responseOverage: TResponseOverageDisplay | null;
  // Free workflow-run allowance derived from the price's free first tier (see TStripeBillingCatalogItem).
  workflowRunsIncluded: number | null;
  // Graduated overage tiers for workflow runs, derived from the price (same shape/source as
  // responseOverage) so the plan card can show the per-unit tier table straight from Stripe.
  workflowRunsOverage: TResponseOverageDisplay | null;
};

export type TStripeBillingCatalogDisplay = {
  hobby: {
    monthly: TStripeBillingCatalogDisplayItem;
  };
  pro: {
    monthly: TStripeBillingCatalogDisplayItem;
    yearly: TStripeBillingCatalogDisplayItem;
  };
  scale: {
    monthly: TStripeBillingCatalogDisplayItem;
    yearly: TStripeBillingCatalogDisplayItem;
  };
};

const STANDARD_CLOUD_PLANS = new Set<TStandardCloudPlan>(["hobby", "pro", "scale"]);
const STRIPE_BILLING_CATALOG_CACHE_TTL_MS = 10 * 60 * 1000;
// v3: catalog item carries workflowRunsPrice (metered workflow overage)
const STRIPE_BILLING_CATALOG_CACHE_VERSION = "v3";

const getStripeBillingCatalogCacheKey = () =>
  createCacheKey.custom(
    "billing",
    "stripe_catalog",
    `${hashString(env.STRIPE_SECRET_KEY ?? "stripe-unconfigured")}-${STRIPE_BILLING_CATALOG_CACHE_VERSION}`
  );

const getPriceProduct = (price: Stripe.Price): Stripe.Product | Stripe.DeletedProduct | null => {
  if (typeof price.product === "string") {
    return null;
  }

  return price.product;
};

const getPricePlan = (price: Stripe.Price): TStandardCloudPlan | null => {
  const product = getPriceProduct(price);
  const plan =
    price.metadata?.formbricks_plan ??
    (!product || product.deleted ? undefined : product.metadata?.formbricks_plan);

  if (!plan || !STANDARD_CLOUD_PLANS.has(plan as TStandardCloudPlan)) {
    return null;
  }

  return plan as TStandardCloudPlan;
};

const normalizeInterval = (interval: string | null | undefined): TCloudBillingInterval | null => {
  if (interval === "month" || interval === "monthly") return "monthly";
  if (interval === "year" || interval === "yearly") return "yearly";
  return null;
};

const getPriceInterval = (price: Stripe.Price): TCloudBillingInterval | null => {
  const metadataInterval = normalizeInterval(price.metadata?.formbricks_interval);
  if (metadataInterval) {
    return metadataInterval;
  }

  return normalizeInterval(price.recurring?.interval);
};

const getPriceKind = (price: Stripe.Price): TStripePriceKind | null => {
  const metadataKind = price.metadata?.formbricks_price_kind;
  if (metadataKind === "base" || metadataKind === "responses" || metadataKind === "workflow_runs") {
    return metadataKind;
  }

  // A metered price tagged with an unrecognized kind is a separate metered product, not part of the
  // plan catalog. Exclude it here so the usage_type fallback below can't misclassify it as
  // "responses" and collide with the real responses price on the same plan/interval (ENG-1936).
  if (metadataKind) {
    return null;
  }

  if (price.recurring?.usage_type === "licensed") {
    return "base";
  }

  if (price.recurring?.usage_type === "metered") {
    return "responses";
  }

  return null;
};

const isCatalogCandidate = (price: Stripe.Price): price is TStripeCatalogPrice => {
  if (!price.active || !price.recurring) {
    return false;
  }

  const product = getPriceProduct(price);
  if (!product || product.deleted || !product.active) {
    return false;
  }

  return getPricePlan(price) !== null && getPriceKind(price) !== null && getPriceInterval(price) !== null;
};

const listAllActivePrices = async (): Promise<TStripeCatalogPrice[]> => {
  if (!stripeClient) {
    return [];
  }

  const prices: TStripeCatalogPrice[] = [];
  let startingAfter: string | undefined;

  do {
    const result = await stripeClient.prices.list({
      active: true,
      limit: 100,
      expand: ["data.product", "data.tiers"],
      ...(startingAfter ? { starting_after: startingAfter } : {}),
    });

    for (const price of result.data) {
      if (isCatalogCandidate(price)) {
        prices.push(price);
      }
    }

    const lastItem = result.data.at(-1);
    startingAfter = result.has_more && lastItem ? lastItem.id : undefined;
  } while (startingAfter);

  return prices;
};

const getSinglePrice = (
  prices: TStripeCatalogPrice[],
  plan: TStandardCloudPlan,
  kind: TStripePriceKind,
  interval: TCloudBillingInterval
): TStripeCatalogPrice => {
  const matches = prices.filter(
    (price) =>
      getPricePlan(price) === plan && getPriceKind(price) === kind && getPriceInterval(price) === interval
  );

  if (matches.length !== 1) {
    throw new Error(
      `Expected exactly one Stripe price for ${plan}/${kind}/${interval}, but found ${matches.length}`
    );
  }

  return matches[0];
};

// Like getSinglePrice, but tolerates absence: returns null when no price matches (the kind is not
// offered on this plan), still throwing on ambiguity (>1) so a duplicate can never be silently
// ignored. Used for optional kinds like workflow_runs that exist only on some plans.
const getOptionalSinglePrice = (
  prices: TStripeCatalogPrice[],
  plan: TStandardCloudPlan,
  kind: TStripePriceKind,
  interval: TCloudBillingInterval
): TStripeCatalogPrice | null => {
  const matches = prices.filter(
    (price) =>
      getPricePlan(price) === plan && getPriceKind(price) === kind && getPriceInterval(price) === interval
  );

  if (matches.length > 1) {
    throw new Error(
      `Expected at most one Stripe price for ${plan}/${kind}/${interval}, but found ${matches.length}`
    );
  }

  return matches[0] ?? null;
};

// Rank for picking the responses price when several active candidates match (ENG-1971). Lower wins.
// Graduated beats the tag: the plan card's overage tooltip and our billing semantics only work with a
// graduated price (toOverageDisplay returns null for anything else), so a volume price must never win
// just because it carries the explicit tag — Stripe copies metadata when a price is duplicated in the
// dashboard, so a legacy price can easily still be tagged "responses". Among prices with the same
// tiers_mode, an explicit formbricks_price_kind tag beats an untagged metered price that only the
// usage_type fallback in getPriceKind classified as responses.
const getResponsePriceRank = (price: TStripeCatalogPrice): [number, number] => [
  price.tiers_mode === "graduated" ? 0 : 1,
  price.metadata?.formbricks_price_kind === "responses" ? 0 : 1,
];

// Deterministic replacement for getSinglePrice on the responses kind. A product can legitimately carry
// a legacy metered price next to the current graduated one (getPriceKind classifies ANY untagged
// metered price as "responses"), and failing the whole catalog on that took the billing page down
// (ENG-1971). Ranking: graduated, then explicitly tagged, then most recent `created`. Still throws when
// nothing matches — a plan without a responses price is a real catalog outage — and logs a warning
// naming the chosen and ignored ids so duplicates stay visible instead of being silently absorbed.
const resolveResponsePrice = (
  prices: TStripeCatalogPrice[],
  plan: TStandardCloudPlan,
  interval: TCloudBillingInterval
): TStripeCatalogPrice => {
  const matches = prices.filter(
    (price) =>
      getPricePlan(price) === plan &&
      getPriceKind(price) === "responses" &&
      getPriceInterval(price) === interval
  );

  if (matches.length === 0) {
    throw new Error(`Expected a Stripe price for ${plan}/responses/${interval}, but found 0`);
  }

  // The usage_type fallback in getPriceKind also catches untagged metered prices of OTHER meters. When a
  // tagged responses price names its meter, only that meter's untagged prices stay in the running, so a
  // foreign-meter price can never outrank it and be attached to checkouts. Without a tagged meter there
  // is nothing to verify against, and ranking alone decides.
  const isResponsesTagged = (price: TStripeCatalogPrice) =>
    price.metadata?.formbricks_price_kind === "responses";
  const getMeter = (price: TStripeCatalogPrice) => price.recurring?.meter ?? null;
  const responseMeters = new Set(
    matches.filter(isResponsesTagged).flatMap((price) => {
      const meter = getMeter(price);
      return meter ? [meter] : [];
    })
  );
  const candidates =
    responseMeters.size === 0
      ? matches
      : matches.filter((price) => isResponsesTagged(price) || responseMeters.has(getMeter(price) ?? ""));
  const foreignMeterIds = matches.filter((price) => !candidates.includes(price)).map((price) => price.id);
  if (foreignMeterIds.length > 0) {
    logger.warn(
      { plan, interval, excludedPriceIds: foreignMeterIds },
      "Excluded untagged metered prices on a different meter from the responses price"
    );
  }

  const [chosen, ...ignored] = [...candidates].sort((a, b) => {
    const [aMode, aTag] = getResponsePriceRank(a);
    const [bMode, bTag] = getResponsePriceRank(b);
    return aMode - bMode || aTag - bTag || b.created - a.created;
  });

  if (ignored.length > 0) {
    // An untagged winner over a skipped tagged price means a metered price we never labelled (possibly a
    // foreign meter) is now billed as responses — escalate so it gets looked at.
    const untaggedBeatTagged = !isResponsesTagged(chosen) && ignored.some(isResponsesTagged);
    const payload = {
      plan,
      interval,
      chosenPriceId: chosen.id,
      chosenTiersMode: chosen.tiers_mode,
      ignoredPriceIds: ignored.map((price) => price.id),
    };
    const message = "Multiple active Stripe responses prices match; using the highest-ranked one";
    if (untaggedBeatTagged) {
      logger.error(payload, message);
    } else {
      logger.warn(payload, message);
    }
  }

  return chosen;
};

// Resolve the included (free) workflow-run allowance from the price's OWN tier structure, and fail
// closed if the price can't honor an "included volume" claim. A graduated price whose first tier is
// free (unit_amount 0, flat_amount 0) up to a finite boundary grants exactly that many free runs —
// the number the usage card shows. Any other shape (flat per-unit, a paid first tier, or an
// unbounded free tier) means the card's "X of N included" would not match what Stripe charges, so we
// throw rather than let a reassuring-but-false allowance render (ENG-2193/2194). The caller catches
// this and degrades the workflow item only, keeping the rest of the catalog up. Returns null when the
// plan has no workflow price at all.
const resolveWorkflowIncludedVolume = (price: TStripeCatalogPrice | null, label: string): number | null => {
  if (!price) {
    return null;
  }

  const firstTier = price.tiers?.[0];
  const firstTierIsFree =
    firstTier != null && (firstTier.unit_amount ?? 0) === 0 && (firstTier.flat_amount ?? 0) === 0;

  if (price.tiers_mode !== "graduated" || !firstTierIsFree || typeof firstTier?.up_to !== "number") {
    throw new Error(
      `Metered workflow price ${label} (${price.id}) must be graduated with a free first tier ` +
        `(unit_amount 0, finite up_to) so the included volume shown to customers matches what Stripe ` +
        `leaves uncharged; got tiers_mode=${price.tiers_mode ?? "null"}, ` +
        `firstTier=${JSON.stringify(firstTier ?? null)}`
    );
  }

  return firstTier.up_to;
};

const fetchStripeBillingCatalog = async (): Promise<TStripeBillingCatalog> => {
  if (!stripeClient) {
    throw new Error("Stripe is not configured");
  }

  const prices = await listAllActivePrices();

  if (prices.length === 0) {
    throw new Error("No active Stripe billing catalog prices found");
  }

  // Resolve the workflow price AND its validated included volume together, so both the price object
  // and the number the UI trusts come from the same source and can't drift.
  //
  // Fail closed on the WORKFLOW ITEM ONLY, not the whole catalog: a misconfigured workflow price
  // (see resolveWorkflowIncludedVolume) drops the workflow price + included volume to null and logs
  // loudly, instead of throwing. The card then hides and new checkouts skip the workflow line item —
  // i.e. workflows simply don't bill, today's harmless state — while base/responses checkout and the
  // billing page for every plan/org stay up. Base/responses themselves stay fail-loud (getSinglePrice
  // throws): they are load-bearing on every plan, so a missing one is a real catalog outage.
  const workflowRuns = (
    plan: TStandardCloudPlan
  ): Pick<TStripeBillingCatalogItem, "workflowRunsPrice" | "workflowRunsIncluded"> => {
    const workflowRunsPrice = getOptionalSinglePrice(prices, plan, "workflow_runs", "monthly");
    try {
      return {
        workflowRunsPrice,
        workflowRunsIncluded: resolveWorkflowIncludedVolume(
          workflowRunsPrice,
          `${plan}/workflow_runs/monthly`
        ),
      };
    } catch (error) {
      logger.error(
        { error, plan, priceId: workflowRunsPrice?.id },
        "Invalid workflow_runs price; excluding it from the catalog so the rest of billing stays up"
      );
      return { workflowRunsPrice: null, workflowRunsIncluded: null };
    }
  };

  // Resolved in the original lookup order (base before responses, so an empty plan still reports its
  // missing base price first). The responses price is resolved once per plan: monthly and yearly items
  // share the same monthly-billed price, and display and checkout both read these items, so they can
  // never pick different prices.
  const hobbyMonthlyBase = getSinglePrice(prices, "hobby", "base", "monthly");
  const proMonthlyBase = getSinglePrice(prices, "pro", "base", "monthly");
  const proResponsePrice = resolveResponsePrice(prices, "pro", "monthly");
  const proYearlyBase = getSinglePrice(prices, "pro", "base", "yearly");
  const scaleMonthlyBase = getSinglePrice(prices, "scale", "base", "monthly");
  const scaleResponsePrice = resolveResponsePrice(prices, "scale", "monthly");
  const scaleYearlyBase = getSinglePrice(prices, "scale", "base", "yearly");

  return {
    hobby: {
      monthly: {
        plan: "hobby",
        interval: "monthly",
        basePrice: hobbyMonthlyBase,
        responsePrice: null,
        ...workflowRuns("hobby"),
      },
    },
    pro: {
      monthly: {
        plan: "pro",
        interval: "monthly",
        basePrice: proMonthlyBase,
        responsePrice: proResponsePrice,
        ...workflowRuns("pro"),
      },
      yearly: {
        plan: "pro",
        interval: "yearly",
        basePrice: proYearlyBase,
        responsePrice: proResponsePrice,
        ...workflowRuns("pro"),
      },
    },
    scale: {
      monthly: {
        plan: "scale",
        interval: "monthly",
        basePrice: scaleMonthlyBase,
        responsePrice: scaleResponsePrice,
        ...workflowRuns("scale"),
      },
      yearly: {
        plan: "scale",
        interval: "yearly",
        basePrice: scaleYearlyBase,
        responsePrice: scaleResponsePrice,
        ...workflowRuns("scale"),
      },
    },
  };
};

export const getStripeBillingCatalog = reactCache(async (): Promise<TStripeBillingCatalog> => {
  return await cache.withCache(
    fetchStripeBillingCatalog,
    getStripeBillingCatalogCacheKey(),
    STRIPE_BILLING_CATALOG_CACHE_TTL_MS
  );
});

// Derive the per-unit overage tier table shown in the plan card straight from a graduated Stripe
// price, so the displayed pricing can never drift from what Stripe charges. Used for both responses
// and workflow-run metered prices. The tier table renders graduated semantics (each band priced
// separately), so volume-mode prices must not be displayed with it.
const toOverageDisplay = (price: TStripeCatalogPrice | null): TResponseOverageDisplay | null => {
  if (price?.tiers_mode !== "graduated") {
    return null;
  }

  const tiers = mapStripeTiersToResponsePricingTiers(price.tiers);
  if (!tiers) {
    return null;
  }

  return { currency: price.currency, tiers };
};

const toDisplayItem = (item: TStripeBillingCatalogItem): TStripeBillingCatalogDisplayItem => ({
  plan: item.plan,
  interval: item.interval,
  currency: item.basePrice.currency,
  unitAmount: item.basePrice.unit_amount,
  responseOverage: toOverageDisplay(item.responsePrice),
  workflowRunsIncluded: item.workflowRunsIncluded,
  workflowRunsOverage: toOverageDisplay(item.workflowRunsPrice),
});

export const getStripeBillingCatalogDisplay = reactCache(async (): Promise<TStripeBillingCatalogDisplay> => {
  const catalog = await getStripeBillingCatalog();

  return {
    hobby: {
      monthly: toDisplayItem(catalog.hobby.monthly),
    },
    pro: {
      monthly: toDisplayItem(catalog.pro.monthly),
      yearly: toDisplayItem(catalog.pro.yearly),
    },
    scale: {
      monthly: toDisplayItem(catalog.scale.monthly),
      yearly: toDisplayItem(catalog.scale.yearly),
    },
  };
});

export const getCatalogItemForPlan = async (
  plan: TStandardCloudPlan,
  interval: TCloudBillingInterval
): Promise<TStripeBillingCatalogItem> => {
  const catalog = await getStripeBillingCatalog();

  if (plan === "hobby") {
    return catalog.hobby.monthly;
  }

  return catalog[plan][interval];
};

export const getCatalogItemsForPlan = async (
  plan: TStandardCloudPlan,
  interval: TCloudBillingInterval
): Promise<Array<{ price: string; quantity?: number }>> => {
  const item = await getCatalogItemForPlan(plan, interval);

  return [
    { price: item.basePrice.id, quantity: 1 },
    ...(item.responsePrice ? [{ price: item.responsePrice.id }] : []),
    // Metered items carry no quantity (usage is reported via meter events).
    ...(item.workflowRunsPrice ? [{ price: item.workflowRunsPrice.id }] : []),
  ];
};

export const getIntervalFromPrice = (
  price: Stripe.Price | null | undefined
): TCloudBillingInterval | null => {
  if (!price) {
    return null;
  }

  return getPriceInterval(price);
};

export const getPlanFromPrice = (price: Stripe.Price | null | undefined): TStandardCloudPlan | null => {
  if (!price) {
    return null;
  }

  return getPricePlan(price);
};

export const getPriceKindFromPrice = (price: Stripe.Price | null | undefined): TStripePriceKind | null => {
  if (!price) {
    return null;
  }

  return getPriceKind(price);
};
