export type TicketTier = "essencial" | "premium" | "vip";

export type CatalogEntry = {
  tier: TicketTier;
  priceId: string;
  amountCents: number;
  currency: string;
};

const catalogEnv: Record<TicketTier, { price?: string; amount?: string }> = {
  essencial: { price: process.env.STRIPE_PRICE_ESSENCIAL, amount: process.env.STRIPE_AMOUNT_ESSENCIAL_CENTS },
  premium: { price: process.env.STRIPE_PRICE_PREMIUM, amount: process.env.STRIPE_AMOUNT_PREMIUM_CENTS },
  vip: { price: process.env.STRIPE_PRICE_VIP, amount: process.env.STRIPE_AMOUNT_VIP_CENTS },
};

export function stripeCatalog(): CatalogEntry[] {
  const currency = (process.env.STRIPE_CURRENCY || "").trim().toLowerCase();
  return (Object.entries(catalogEnv) as Array<[TicketTier, { price?: string; amount?: string }]>).flatMap(([tier, config]) => {
    const priceId = (config.price || "").trim();
    const amountCents = Number(config.amount);
    if (!priceId || !currency || !Number.isSafeInteger(amountCents) || amountCents <= 0) return [];
    return [{ tier, priceId, amountCents, currency }];
  });
}

export function catalogEntryForTier(tier: string) {
  return stripeCatalog().find((entry) => entry.tier === tier);
}

export function catalogEntryForPrice(priceId: string) {
  return stripeCatalog().find((entry) => entry.priceId === priceId);
}

export function isCheckoutConfigurationComplete() {
  const entries = stripeCatalog();
  return entries.length === 3 && new Set(entries.map((entry) => entry.priceId)).size === 3;
}

