// Subscription Types for ShopCall.ai

// Enum types matching database
export type SubscriptionStatus = 'trial' | 'active' | 'past_due' | 'cancelled' | 'expired';
export type BillingPeriod = 'trial' | 'monthly' | 'yearly';
export type Currency = 'HUF' | 'EUR' | 'USD';

// Subscription Plan
export interface SubscriptionPlan {
  id: string;
  plan_code: string;
  sort_order: number;
  is_active: boolean;
  is_trial: boolean;
  is_popular: boolean;
  price_huf: number;
  price_eur: number;
  price_usd: number;
  overage_price_huf: number | null;
  overage_price_eur: number | null;
  overage_price_usd: number | null;
  minutes_included: number;
  trial_days: number | null;
  max_products: number | null;
  icon_name: string | null;
  badge_color: string | null;
  created_at: string;
  updated_at: string;
}

// Plan Translation
export interface SubscriptionPlanTranslation {
  id: string;
  plan_id: string;
  language_code: string;
  name: string;
  description: string | null;
  period_label: string | null;
  overage_label: string | null;
  badge_text: string | null;
  created_at: string;
  updated_at: string;
}

// Plan Feature
export interface SubscriptionPlanFeature {
  id: string;
  plan_id: string;
  feature_code: string;
  sort_order: number;
  is_highlighted: boolean;
  created_at: string;
}

// Feature Translation
export interface SubscriptionFeatureTranslation {
  id: string;
  feature_id: string;
  language_code: string;
  label: string;
  created_at: string;
}

// Additional Package
export interface AdditionalPackage {
  id: string;
  package_code: string;
  sort_order: number;
  is_active: boolean;
  minutes: number;
  price_huf: number;
  price_eur: number;
  price_usd: number;
  created_at: string;
  updated_at: string;
}

// Package Translation
export interface AdditionalPackageTranslation {
  id: string;
  package_id: string;
  language_code: string;
  name: string;
  description: string | null;
  created_at: string;
}

// Store Subscription
export interface StoreSubscription {
  id: string;
  store_id: string;
  plan_id: string;
  status: SubscriptionStatus;
  billing_period: BillingPeriod;
  period_start: string;
  period_end: string;
  minutes_used: number;
  minutes_included: number;
  auto_purchase_enabled: boolean;
  auto_purchase_package_id: string | null;
  auto_purchase_threshold: number;
  currency: Currency;
  cancelled_at: string | null;
  cancellation_reason: string | null;
  created_at: string;
  updated_at: string;
}

// Package Purchase
export interface PackagePurchase {
  id: string;
  store_id: string;
  subscription_id: string;
  package_id: string;
  minutes_purchased: number;
  minutes_remaining: number;
  currency: Currency;
  price_paid: number;
  is_auto_purchase: boolean;
  expires_at: string;
  purchased_at: string;
  is_active: boolean;
}

// Billing History
export interface BillingHistoryItem {
  id: string;
  store_id: string;
  subscription_id: string | null;
  event_type: string;
  currency: Currency;
  amount: number;
  plan_id: string | null;
  package_id: string | null;
  metadata: Record<string, unknown>;
  description: string | null;
  created_at: string;
}

// =============================================================================
// Joined/Composite Types for Frontend Use
// =============================================================================

// Plan with translation (for display)
export interface PlanWithTranslation extends SubscriptionPlan {
  translations: SubscriptionPlanTranslation;
  features: FeatureWithTranslation[];
}

// Feature with translation
export interface FeatureWithTranslation extends SubscriptionPlanFeature {
  translations: SubscriptionFeatureTranslation;
}

// Package with translation
export interface PackageWithTranslation extends AdditionalPackage {
  translations: AdditionalPackageTranslation;
}

// Subscription with plan details (for sidebar display)
export interface SubscriptionWithPlan extends StoreSubscription {
  plan: SubscriptionPlan;
  plan_translation?: SubscriptionPlanTranslation;
}

// Full subscription data (for billing page)
export interface FullSubscriptionData {
  subscription: StoreSubscription;
  plan: PlanWithTranslation;
  active_packages: PackagePurchase[];
  total_minutes_remaining: number;
  package_minutes_remaining: number;
  is_expired: boolean;
  days_remaining: number;
}

// =============================================================================
// Helper Functions
// =============================================================================

/**
 * Get price for a plan based on currency
 */
export function getPlanPrice(plan: SubscriptionPlan, currency: Currency): number {
  switch (currency) {
    case 'HUF':
      return plan.price_huf;
    case 'EUR':
      return plan.price_eur;
    case 'USD':
      return plan.price_usd;
    default:
      return plan.price_huf;
  }
}

/**
 * Get overage price for a plan based on currency
 */
export function getOveragePrice(plan: SubscriptionPlan, currency: Currency): number | null {
  switch (currency) {
    case 'HUF':
      return plan.overage_price_huf;
    case 'EUR':
      return plan.overage_price_eur;
    case 'USD':
      return plan.overage_price_usd;
    default:
      return plan.overage_price_huf;
  }
}

/**
 * Get package price based on currency
 */
export function getPackagePrice(pkg: AdditionalPackage, currency: Currency): number {
  switch (currency) {
    case 'HUF':
      return pkg.price_huf;
    case 'EUR':
      return pkg.price_eur;
    case 'USD':
      return pkg.price_usd;
    default:
      return pkg.price_huf;
  }
}

/**
 * Format currency amount
 */
export function formatCurrency(amount: number, currency: Currency): string {
  switch (currency) {
    case 'HUF':
      return `${amount.toLocaleString('hu-HU')} Ft`;
    case 'EUR':
      return `€${amount.toLocaleString('de-DE')}`;
    case 'USD':
      return `$${amount.toLocaleString('en-US')}`;
    default:
      return `${amount}`;
  }
}

/**
 * Calculate minutes remaining (included + packages)
 */
export function calculateMinutesRemaining(
  subscription: StoreSubscription,
  activePackages: PackagePurchase[]
): { included: number; packages: number; total: number } {
  const includedRemaining = Math.max(subscription.minutes_included - subscription.minutes_used, 0);
  const packageRemaining = activePackages.reduce((sum, pkg) => sum + pkg.minutes_remaining, 0);

  return {
    included: includedRemaining,
    packages: packageRemaining,
    total: includedRemaining + packageRemaining
  };
}

/**
 * Check if subscription is expired (by time or minutes for trial)
 */
export function isSubscriptionExpired(subscription: StoreSubscription): boolean {
  const now = new Date();
  const periodEnd = new Date(subscription.period_end);

  // Time expired
  if (now > periodEnd) {
    return true;
  }

  // For trial, also check minutes
  if (subscription.status === 'trial') {
    const minutesRemaining = subscription.minutes_included - subscription.minutes_used;
    if (minutesRemaining <= 0) {
      return true;
    }
  }

  return false;
}

/**
 * Get usage percentage (0-100)
 */
export function getUsagePercentage(subscription: StoreSubscription): number {
  if (subscription.minutes_included === 0) return 100;
  return Math.min((subscription.minutes_used / subscription.minutes_included) * 100, 100);
}

/**
 * Get usage status color class
 */
export function getUsageStatusColor(percentage: number): string {
  if (percentage >= 90) return 'text-red-500';
  if (percentage >= 75) return 'text-yellow-500';
  return 'text-green-500';
}

/**
 * Get usage progress bar color class
 */
export function getUsageProgressColor(percentage: number): string {
  if (percentage >= 90) return 'bg-red-500';
  if (percentage >= 75) return 'bg-yellow-500';
  return 'bg-cyan-500';
}
