/**
 * Subscription API Types - Mirror backend centralized plans configuration
 * Source: /shared/subscription/plans.py
 */

// ============================================================================
// SUBSCRIPTION PLAN ENUMS
// ============================================================================

export const SUBSCRIPTION_TIERS = {
  STARTER: 'starter',
  PROFESSIONAL: 'professional',
  ENTERPRISE: 'enterprise'
} as const;

export type SubscriptionTier = typeof SUBSCRIPTION_TIERS[keyof typeof SUBSCRIPTION_TIERS];

export const BILLING_CYCLES = {
  MONTHLY: 'monthly',
  YEARLY: 'yearly'
} as const;

export type BillingCycle = typeof BILLING_CYCLES[keyof typeof BILLING_CYCLES];

// ============================================================================
// QUOTA LIMITS
// ============================================================================

export interface QuotaLimits {
  // Team & Organization
  max_users?: number | null;  // null = unlimited
  max_locations?: number | null;

  // Product & Inventory
  max_products?: number | null;
  max_recipes?: number | null;
  max_suppliers?: number | null;

  // ML & Analytics (Daily)
  training_jobs_per_day?: number | null;
  forecast_generation_per_day?: number | null;

  // Data Limits
  dataset_size_rows?: number | null;
  forecast_horizon_days?: number | null;
  historical_data_access_days?: number | null;

  // Import/Export
  bulk_import_rows?: number | null;
  bulk_export_rows?: number | null;

  // Integrations
  pos_sync_interval_minutes?: number | null;
  api_calls_per_hour?: number | null;
  webhook_endpoints?: number | null;

  // Storage
  file_storage_gb?: number | null;
  report_retention_days?: number | null;
}

// ============================================================================
// PLAN FEATURES
// ============================================================================

export interface PlanFeatures {
  // Core features (all tiers)
  inventory_management: boolean;
  sales_tracking: boolean;
  basic_recipes: boolean;
  production_planning: boolean;
  basic_reporting: boolean;
  mobile_app_access: boolean;
  email_support: boolean;
  easy_step_by_step_onboarding: boolean;

  // Starter+ features
  basic_forecasting?: boolean;
  demand_prediction?: boolean;
  waste_tracking?: boolean;
  order_management?: boolean;
  customer_management?: boolean;
  supplier_management?: boolean;
  batch_tracking?: boolean;
  expiry_alerts?: boolean;

  // Professional+ features
  advanced_analytics?: boolean;
  custom_reports?: boolean;
  sales_analytics?: boolean;
  supplier_performance?: boolean;
  waste_analysis?: boolean;
  profitability_analysis?: boolean;
  weather_data_integration?: boolean;
  traffic_data_integration?: boolean;
  multi_location_support?: boolean;
  location_comparison?: boolean;
  inventory_transfer?: boolean;
  batch_scaling?: boolean;
  recipe_feasibility_check?: boolean;
  seasonal_patterns?: boolean;
  longer_forecast_horizon?: boolean;
  pos_integration?: boolean;
  accounting_export?: boolean;
  basic_api_access?: boolean;
  priority_email_support?: boolean;
  phone_support?: boolean;

  // Enterprise features
  scenario_modeling?: boolean;
  what_if_analysis?: boolean;
  risk_assessment?: boolean;
  advanced_ml_parameters?: boolean;
  model_artifacts_access?: boolean;
  custom_algorithms?: boolean;
  full_api_access?: boolean;
  unlimited_webhooks?: boolean;
  erp_integration?: boolean;
  custom_integrations?: boolean;
  multi_tenant_management?: boolean;
  white_label_option?: boolean;
  custom_branding?: boolean;
  sso_saml?: boolean;
  advanced_permissions?: boolean;
  audit_logs_export?: boolean;
  compliance_reports?: boolean;
  benchmarking?: boolean;
  competitive_analysis?: boolean;
  market_insights?: boolean;
  predictive_maintenance?: boolean;
  dedicated_account_manager?: boolean;
  priority_support?: boolean;
  support_24_7?: boolean;
  custom_training?: boolean;
  onsite_support?: boolean;
}

// ============================================================================
// PLAN METADATA
// ============================================================================

export interface PlanMetadata {
  name: string;
  description: string;
  tagline: string;
  popular: boolean;
  monthly_price: number;
  yearly_price: number;
  trial_days: number;
  features: string[];  // List of feature keys
  limits: {
    users: number | null;
    locations: number | null;
    products: number | null;
    forecasts_per_day: number | null;
  };
  support: string;
  recommended_for: string;
  contact_sales?: boolean;
}

export interface AvailablePlans {
  plans: {
    [key in SubscriptionTier]: PlanMetadata;
  };
}

// ============================================================================
// USAGE & SUBSCRIPTION STATUS
// ============================================================================

export interface UsageMetric {
  current: number;
  limit: number | null;
  unlimited: boolean;
  usage_percentage: number;
}

export interface CurrentUsage {
  // Team & Organization
  users: UsageMetric;
  locations: UsageMetric;

  // Product & Inventory
  products: UsageMetric;
  recipes: UsageMetric;
  suppliers: UsageMetric;

  // ML & Analytics (Daily)
  training_jobs_today: UsageMetric;
  forecasts_today: UsageMetric;

  // API Usage (Hourly)
  api_calls_this_hour: UsageMetric;

  // Storage
  file_storage_used_gb: UsageMetric;
}

export interface UsageSummary {
  plan: SubscriptionTier;
  status: 'active' | 'inactive' | 'trialing' | 'past_due' | 'cancelled';
  billing_cycle: BillingCycle;
  monthly_price: number;
  next_billing_date: string;
  trial_ends_at?: string;
  usage: CurrentUsage;
}

// ============================================================================
// FEATURE & QUOTA CHECKS
// ============================================================================

export interface FeatureCheckRequest {
  feature_name: string;
  tenant_id: string;
}

export interface FeatureCheckResponse {
  enabled: boolean;
  requires_upgrade: boolean;
  required_tier?: SubscriptionTier;
  message?: string;
}

export interface QuotaCheckRequest {
  quota_type: string;
  tenant_id: string;
  requested_amount?: number;
}

export interface QuotaCheckResponse {
  allowed: boolean;
  current: number;
  limit: number | null;
  remaining: number | null;
  reset_at?: string;
  message?: string;
}

// ============================================================================
// PLAN MANAGEMENT
// ============================================================================

export interface PlanUpgradeValidation {
  can_upgrade: boolean;
  from_tier: SubscriptionTier;
  to_tier: SubscriptionTier;
  price_difference: number;
  prorated_amount?: number;
  reason?: string;
}

export interface PlanUpgradeRequest {
  tenant_id: string;
  new_tier: SubscriptionTier;
  billing_cycle: BillingCycle;
}

export interface PlanUpgradeResult {
  success: boolean;
  message: string;
  new_plan: SubscriptionTier;
  effective_date?: string;
  old_plan?: string;
  new_monthly_price?: number;
  validation?: any;
  requires_token_refresh?: boolean; // Backend signals that token should be refreshed
  // Trial handling fields
  is_trialing?: boolean;
  trial_ends_at?: string;
  stripe_updated?: boolean;
  trial_preserved?: boolean;
}

export interface SubscriptionInvoice {
  id: string;
  date: string;
  amount: number;
  status: 'paid' | 'pending' | 'failed';
  period_start: string;
  period_end: string;
  download_url?: string;
}

// ============================================================================
// HELPERS
// ============================================================================

// Plan hierarchy for comparison
export const PLAN_HIERARCHY: Record<SubscriptionTier, number> = {
  [SUBSCRIPTION_TIERS.STARTER]: 1,
  [SUBSCRIPTION_TIERS.PROFESSIONAL]: 2,
  [SUBSCRIPTION_TIERS.ENTERPRISE]: 3
};

/**
 * Check if a plan meets minimum tier requirement
 */
export function doesPlanMeetMinimum(
  userPlan: SubscriptionTier,
  requiredPlan: SubscriptionTier
): boolean {
  return PLAN_HIERARCHY[userPlan] >= PLAN_HIERARCHY[requiredPlan];
}

/**
 * Get plan display color
 */
export function getPlanColor(tier: SubscriptionTier): string {
  switch (tier) {
    case SUBSCRIPTION_TIERS.STARTER:
      return 'blue';
    case SUBSCRIPTION_TIERS.PROFESSIONAL:
      return 'purple';
    case SUBSCRIPTION_TIERS.ENTERPRISE:
      return 'amber';
    default:
      return 'gray';
  }
}

/**
 * Calculate discount percentage for yearly billing
 */
export function getYearlyDiscountPercentage(monthlyPrice: number, yearlyPrice: number): number {
  const yearlyAnnual = monthlyPrice * 12;
  const discount = ((yearlyAnnual - yearlyPrice) / yearlyAnnual) * 100;
  return Math.round(discount);
}

// ============================================================================
// ANALYTICS LEVELS (for route-based analytics restrictions)
// ============================================================================

export const ANALYTICS_LEVELS = {
  NONE: 'none',
  BASIC: 'basic',
  ADVANCED: 'advanced',
  PREDICTIVE: 'predictive'
} as const;

export type AnalyticsLevel = typeof ANALYTICS_LEVELS[keyof typeof ANALYTICS_LEVELS];

export const ANALYTICS_HIERARCHY: Record<AnalyticsLevel, number> = {
  [ANALYTICS_LEVELS.NONE]: 0,
  [ANALYTICS_LEVELS.BASIC]: 1,
  [ANALYTICS_LEVELS.ADVANCED]: 2,
  [ANALYTICS_LEVELS.PREDICTIVE]: 3
};
