export type PlanId = "free" | "plus" | "pro";
export type BillingInterval = "monthly" | "yearly";

export interface PlanLimits {
  maxExpenses: number | null; // null = unlimited
  maxGoals: number | null;
  maxBudgetCategories: number | null;
  advancedReports: boolean;
  export: boolean;
  planning: boolean;
}

export interface Plan {
  id: PlanId;
  priceMonthly: number; // in EUR, display currency handled separately
  priceYearly: number;
  stripePriceIdEnvKeyMonthly: string | null;
  stripePriceIdEnvKeyYearly: string | null;
  limits: PlanLimits;
}

/**
 * Single source of truth for pricing + entitlements. Every place in the
 * app (pricing page, checkout, feature gates, admin MRR calc) reads from
 * here instead of hardcoding numbers.
 */
export const PLANS: Record<PlanId, Plan> = {
  free: {
    id: "free",
    priceMonthly: 0,
    priceYearly: 0,
    stripePriceIdEnvKeyMonthly: null,
    stripePriceIdEnvKeyYearly: null,
    limits: {
      maxExpenses: 50,
      maxGoals: 1,
      maxBudgetCategories: 3,
      advancedReports: false,
      export: false,
      planning: false
    }
  },
  plus: {
    id: "plus",
    priceMonthly: 4.99,
    priceYearly: 49.9, // ~2 months free
    stripePriceIdEnvKeyMonthly: "STRIPE_PRICE_PLUS_MONTHLY",
    stripePriceIdEnvKeyYearly: "STRIPE_PRICE_PLUS_YEARLY",
    limits: {
      maxExpenses: null,
      maxGoals: null,
      maxBudgetCategories: null,
      advancedReports: true,
      export: false,
      planning: true
    }
  },
  pro: {
    id: "pro",
    priceMonthly: 9.99,
    priceYearly: 99.9,
    stripePriceIdEnvKeyMonthly: "STRIPE_PRICE_PRO_MONTHLY",
    stripePriceIdEnvKeyYearly: "STRIPE_PRICE_PRO_YEARLY",
    limits: {
      maxExpenses: null,
      maxGoals: null,
      maxBudgetCategories: null,
      advancedReports: true,
      export: true,
      planning: true
    }
  }
};

export function getPlan(id: PlanId): Plan {
  return PLANS[id];
}

export function formatPrice(amount: number, currency: string = "EUR", locale = "en") {
  return new Intl.NumberFormat(locale === "pl" ? "pl-PL" : "en-US", {
    style: "currency",
    currency,
    minimumFractionDigits: amount % 1 === 0 ? 0 : 2
  }).format(amount);
}

export function isWithinLimit(current: number, limit: number | null): boolean {
  if (limit === null) return true;
  return current < limit;
}
