/**
 * Customer Health Score Type Definitions
 *
 * Interfaces for customer health scoring, at-risk detection,
 * and renewal risk management.
 *
 * @module types/health-score
 */

/**
 * Health status categories based on composite score
 * healthy: >= 70, at_risk: 40-69, critical: < 40
 */
export type HealthStatus = 'healthy' | 'at_risk' | 'critical';

/**
 * Risk level categories for at-risk detection
 */
export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';

/**
 * Types of usage cliff detection periods
 */
export type UsageCliffType =
  | 'usage_cliff_7d'
  | 'usage_cliff_14d'
  | 'usage_cliff_28d'
  | 'support_spike'
  | 'payment_failed'
  | 'no_login';

/**
 * Playbook recommendations for at-risk accounts
 */
export type SuggestedPlaybook = 'recovery_sequence' | 'qbr' | 'csm_outreach';

/**
 * Recovery sequence types for playbook actions
 */
export type RecoverySequenceType = 'gentle_reminder' | 'value_highlight' | 'urgent_save';

/**
 * Health score breakdown by category
 */
export interface HealthScoreBreakdown {
  /** Usage score (0-40): login frequency, feature depth, message volume */
  usage: number;
  /** Support score (0-30): ticket volume, resolution time, sentiment */
  support: number;
  /** Payment score (0-30): on-time payments, dunning history, plan tier */
  payment: number;
}

/**
 * Complete health score for an account
 */
export interface HealthScore {
  /** Composite health score (0-100) */
  total: number;
  /** Score breakdown by category */
  breakdown: HealthScoreBreakdown;
  /** Health status based on total score */
  status: HealthStatus;
}

/**
 * Risk reason for at-risk accounts
 */
export interface RiskReason {
  /** Type of risk detected */
  type: UsageCliffType;
  /** Severity of the risk (0-100) */
  severity: number;
  /** Human-readable description */
  detail: string;
}

/**
 * At-risk account with health score and risk factors
 */
export interface AtRiskAccount {
  /** User/tenant ID */
  tenantId: string;
  /** User/company name */
  tenantName: string;
  /** User email */
  tenantEmail: string;
  /** Current health score (0-100) */
  healthScore: number;
  /** Health status */
  healthStatus: HealthStatus;
  /** Risk level classification */
  riskLevel: RiskLevel;
  /** List of risk factors */
  riskReasons: RiskReason[];
  /** Recommended playbook action */
  suggestedPlaybook: SuggestedPlaybook;
  /** Last time this account was contacted */
  lastContactedAt: string | null;
  /** Subscription tier */
  tier: string | null;
  /** Monthly recurring revenue for this account */
  mrr: number;
}

/**
 * Account health record with full details
 */
export interface AccountHealth {
  /** User ID */
  userId: string;
  /** User name */
  name: string | null;
  /** Company name */
  companyName: string | null;
  /** Email address */
  email: string;
  /** Complete health score */
  healthScore: HealthScore;
  /** Current subscription status */
  subscriptionStatus: string | null;
  /** Subscription tier */
  tier: string | null;
  /** MRR for the account */
  mrr: number;
  /** Last login timestamp */
  lastLoginAt: string | null;
  /** Number of support tickets (last 30 days) */
  supportTickets30d: number;
  /** Payment failure count */
  paymentFailures: number;
}

/**
 * Health distribution summary
 */
export interface HealthDistribution {
  /** Accounts with healthy status (>= 70) */
  healthy: number;
  /** Accounts with at_risk status (40-69) */
  atRisk: number;
  /** Accounts with critical status (< 40) */
  critical: number;
  /** Total accounts */
  total: number;
}

/**
 * Customer health API response
 */
export interface CustomerHealthResponse {
  /** Health distribution summary */
  distribution: HealthDistribution;
  /** List of all account health scores */
  accounts: AccountHealth[];
  /** Top at-risk accounts needing attention */
  atRiskAccounts: AtRiskAccount[];
  /** Average health score across all accounts */
  averageHealthScore: number;
  /** Trend vs previous period (positive = improving) */
  trend: number;
  /** Timestamp when data was calculated */
  calculatedAt: string;
}

/**
 * Renewal information for an account
 */
export interface RenewalInfo {
  /** User ID */
  userId: string;
  /** User name */
  name: string | null;
  /** Company name */
  companyName: string | null;
  /** Email address */
  email: string;
  /** Next renewal date */
  renewalDate: string;
  /** Days until renewal */
  daysUntilRenewal: number;
  /** Subscription tier */
  tier: string | null;
  /** Billing period (monthly/yearly) */
  billingPeriod: string | null;
  /** Health score (0-100) */
  healthScore: number;
  /** Health status */
  healthStatus: HealthStatus;
  /** Renewal risk level */
  renewalRisk: RiskLevel;
  /** MRR at risk if churns */
  mrrAtRisk: number;
  /** Number of payment failures */
  paymentFailures: number;
  /** Has active dunning */
  isDunning: boolean;
}

/**
 * Churned account information
 */
export interface ChurnedAccount {
  /** User ID */
  userId: string;
  /** User name */
  name: string | null;
  /** Company name */
  companyName: string | null;
  /** Email address */
  email: string;
  /** Date of churn */
  churnedAt: string;
  /** Previous tier before churn */
  previousTier: string | null;
  /** Lost MRR */
  lostMrr: number;
  /** Reason for churn (if available) */
  churnReason: string | null;
  /** Total time as customer (days) */
  lifetimeDays: number;
}

/**
 * Renewals API response
 */
export interface RenewalsResponse {
  /** Renewals in next 30 days */
  next30Days: RenewalInfo[];
  /** Renewals in 31-60 days */
  next60Days: RenewalInfo[];
  /** Renewals in 61-90 days */
  next90Days: RenewalInfo[];
  /** Accounts in dunning status */
  dunning: {
    userId: string;
    name: string | null;
    email: string;
    failureCount: number;
    lastAttempt: string | null;
    nextRetry: string | null;
    amount: number;
  }[];
  /** Recently churned accounts */
  churned30Days: ChurnedAccount[];
  /** Total revenue at risk (next 90 days) */
  totalRevenueAtRisk: number;
  /** Summary stats */
  summary: {
    totalUpcoming: number;
    highRiskCount: number;
    dunningCount: number;
    churnedCount: number;
  };
}

/**
 * Recovery sequence request
 */
export interface RecoverySequenceRequest {
  /** Target tenant/user ID */
  tenantId: string;
  /** Type of recovery sequence to trigger */
  sequenceType: RecoverySequenceType;
}

/**
 * Schedule QBR request
 */
export interface ScheduleQBRRequest {
  /** Target tenant/user ID */
  tenantId: string;
  /** Suggested dates for QBR (ISO strings) */
  suggestedDates: string[];
  /** Attendee email addresses */
  attendees: string[];
}

/**
 * Playbook action result
 */
export interface PlaybookActionResult {
  /** Whether action was successful */
  success: boolean;
  /** Action type that was executed */
  actionType: string;
  /** Target tenant ID */
  tenantId: string;
  /** Result message */
  message: string;
  /** Timestamp of action */
  executedAt: string;
}

/**
 * Usage metrics for health score calculation
 */
export interface UsageMetrics {
  /** Total logins in the period */
  loginCount: number;
  /** Days since last login */
  daysSinceLastLogin: number;
  /** Number of active days */
  activeDays: number;
  /** Number of conversations */
  conversationCount: number;
  /** Number of messages sent */
  messagesSent: number;
  /** Number of workflows used */
  workflowsActive: number;
}

/**
 * Support metrics for health score calculation
 */
export interface SupportMetrics {
  /** Open tickets */
  openTickets: number;
  /** Tickets created in period */
  ticketsCreated: number;
  /** Average resolution time (hours) */
  avgResolutionTime: number;
  /** Urgent tickets */
  urgentTickets: number;
}

/**
 * Payment metrics for health score calculation
 */
export interface PaymentMetrics {
  /** Subscription status */
  status: string;
  /** Number of failed payments */
  failureCount: number;
  /** Days since last payment */
  daysSinceLastPayment: number;
  /** Current tier */
  tier: string | null;
  /** Whether in dunning */
  isDunning: boolean;
}
