export const BILLING_PRODUCTS = {
  FREE: 'free',
  PREMIUM_MONTHLY: 'pr_monthly',
  PREMIUM_YEARLY: 'pr_yearly',
  CREDITS_10: '10_credits',
  CREDITS_100: '100_credits',
  CREDITS_500: '500_credits',
} as const;

export const BILLING_PRODUCT_ALIASES = {
  monthly: [
    'pr_monthly',
    'com.thefurfinder.app.premium.monthly',
    'com.app.premium.monthly',
    'premium-monthly',
  ],
  yearly: ['pr_yearly', 'com.thefurfinder.app.premium.annually', 'com.app.premium.yearly', 'premium-yearly'],
  credits10: ['10_credits'],
  credits100: ['100_credits'],
  credits500: ['500_credits'],
} as const;

export type BillingProductId = string;

export const ALL_BILLING_PRODUCTS: BillingProductId[] = [
  ...BILLING_PRODUCT_ALIASES.monthly,
  ...BILLING_PRODUCT_ALIASES.yearly,
  ...BILLING_PRODUCT_ALIASES.credits10,
  ...BILLING_PRODUCT_ALIASES.credits100,
  ...BILLING_PRODUCT_ALIASES.credits500,
];

export const CREDIT_PACKAGES: Record<
  string,
  {
    credits: number;
    priceUsd: number;
    discountLabel?: string;
  }
> = {
  '10_credits': { credits: 5, priceUsd: 1.99 },
  '100_credits': { credits: 30, priceUsd: 9.99, discountLabel: '16%' },
  '500_credits': { credits: 100, priceUsd: 24.99, discountLabel: '37%' },
};

export function isKnownBillingProduct(productId?: string): productId is BillingProductId {
  return !!productId && ALL_BILLING_PRODUCTS.includes(productId);
}

export function isSubscriptionProduct(productId?: string): boolean {
  if (!productId) return false;
  return (
    BILLING_PRODUCT_ALIASES.monthly.includes(productId as any) ||
    BILLING_PRODUCT_ALIASES.yearly.includes(productId as any)
  );
}

export function isCreditProduct(productId?: string): boolean {
  if (!productId) return false;
  return Object.prototype.hasOwnProperty.call(CREDIT_PACKAGES, productId);
}

export function getCreditPackage(productId?: string) {
  if (!productId) return null;
  return CREDIT_PACKAGES[productId] || null;
}

export function planFromProductId(productId?: string): 'pr_monthly' | 'pr_yearly' {
  if (productId && BILLING_PRODUCT_ALIASES.yearly.includes(productId as any)) {
    return 'pr_yearly';
  }
  return 'pr_monthly';
}
