import type {
  Package,
  Subscription,
  SubscriptionCredits,
} from './packages-types';

export function getActivePackage(
  subscription: Subscription | null,
  packages: Package[],
): Package | null {
  if (!subscription) return null;
  return packages.find((pkg) => pkg.id === subscription.packageId) ?? null;
}

export function isConsultationLimitReached(
  credits: SubscriptionCredits | null,
): boolean {
  return (
    !!credits &&
    credits.consultationsTotal !== null &&
    credits.consultationsUsed >= credits.consultationsTotal
  );
}

export function consultationAccessMessage(
  subscription: Subscription | null,
  activePackage: Package | null,
  credits: SubscriptionCredits | null,
): string | null {
  if (!subscription) {
    return 'Choose a package before booking. Your package controls consultation credits, EMR access, family members, and device limits.';
  }
  if (!isConsultationLimitReached(credits)) return null;
  if (activePackage?.tierType === 'payg') {
    return 'Your paid appointment has been used. Buy another Pay-As-You-Go appointment before booking again.';
  }
  if (activePackage?.tierType === 'bundle') {
    return 'Your bundle consultation credits are finished. Buy another bundle or request a subscription upgrade before booking again.';
  }
  if ((activePackage?.addonAppointmentPrice ?? 0) > 0) {
    return 'Your included subscription consultations are finished. Request a paid add-on or plan upgrade before booking again.';
  }
  return 'Your included consultation credits are finished. Request a plan upgrade before booking again.';
}

export function consultationAccessCta(
  activePackage: Package | null,
): string {
  if (activePackage?.tierType === 'payg') return 'Buy another appointment';
  if (activePackage?.tierType === 'bundle') return 'Buy another bundle';
  if ((activePackage?.addonAppointmentPrice ?? 0) > 0) return 'Request paid add-on';
  return 'Review packages';
}
