import type { BillingCycle, PlanTier } from "@/types";

export interface PlanDefinition {
  tier: PlanTier;
  name: string;
  description: string;
  monthlyPriceCents: number;
  annualPriceCents: number;
  responseQuotaLimit: number;
  features: string[];
  featured?: boolean;
  contactSales?: boolean;
}

export const PLAN_DEFINITIONS: Record<PlanTier, PlanDefinition> = {
  free: {
    tier: "free",
    name: "Free",
    description: "For getting a first survey out the door.",
    monthlyPriceCents: 0,
    annualPriceCents: 0,
    responseQuotaLimit: 100,
    features: [
      "100 responses/mo",
      "3 active surveys",
      "Basic question types",
    ],
  },
  pro: {
    tier: "pro",
    name: "Pro",
    description: "For growing teams running regular research.",
    monthlyPriceCents: 3900,
    annualPriceCents: 37200,
    responseQuotaLimit: 10000,
    featured: true,
    features: [
      "10,000 responses/mo",
      "Unlimited surveys",
      "Logic jump & branching",
      "Custom branding",
    ],
  },
  enterprise: {
    tier: "enterprise",
    name: "Enterprise",
    description: "For orgs needing SSO, SLAs, and white-label.",
    monthlyPriceCents: 0,
    annualPriceCents: 0,
    responseQuotaLimit: 999999,
    contactSales: true,
    features: [
      "Unlimited responses",
      "White-label / custom domain",
      "SSO & audit logs",
    ],
  },
};

/** Effective monthly revenue in cents for MRR calculations. */
export function planMrrCents(
  tier: PlanTier,
  billingCycle: BillingCycle
): number {
  const plan = PLAN_DEFINITIONS[tier];
  if (tier === "free") return 0;
  if (tier === "enterprise") return 99000;
  if (billingCycle === "annual") {
    return Math.round(plan.annualPriceCents / 12);
  }
  return plan.monthlyPriceCents;
}

export function formatPlanPrice(cents: number, cycle: BillingCycle): string {
  if (cents === 0) return "$0";
  const monthly =
    cycle === "annual" ? Math.round(cents / 12) : cents;
  return `$${Math.round(monthly / 100)}`;
}

/** Resolve Stripe price ID from env for checkout. */
export function getStripePriceId(
  tier: PlanTier,
  billingCycle: BillingCycle
): string | null {
  if (tier !== "pro") return null;
  if (billingCycle === "annual") {
    return process.env.STRIPE_PRICE_PRO_ANNUAL ?? null;
  }
  return process.env.STRIPE_PRICE_PRO_MONTHLY ?? null;
}

export function isStripeConfigured(): boolean {
  return Boolean(process.env.STRIPE_SECRET_KEY);
}
