// SCRUM-303 — Customer Health & Adoption Analytics domain types.
// Field names are snake_case to match the /api/admin/health/* JSON exactly.

export type HealthPeriod = "month" | "week" | "3months" | "custom";

export type HealthTier = "healthy" | "attention" | "at_risk";

export type HealthAlertSeverity = "red" | "amber";

export interface HealthTierBucket {
  count: number;
  share: number;
}

// ── Executive Dashboard (Level 1) ────────────────────────────────────────────

export interface HealthChurnRiskItem {
  company_user_id: number;
  company: string;
  health: number;
  reason: string | null;
  last_login_days: number | null;
}

export interface HealthModuleUtilization {
  key: string;
  label: string;
  avg_pct: number;
}

export interface HealthExecutive {
  period: { key: string; start: string; end: string };
  needs_compute: boolean;
  portfolio_score: number | null;
  tiers: { healthy: number; at_risk: number };
  clients: {
    total: number;
    active: number;
    inactive: number;
    new: number;
    churn_risk: number;
  };
  users: {
    total: number;
    active_today: number;
    active_week: number;
    active_month: number;
  };
  adoption: {
    avg_login_frequency: number;
    avg_modules: number;
    avg_session_minutes: number | null;
    avg_feature_adoption: number;
  };
  engagement: {
    actions_per_week: number;
    current: number;
    previous: number;
    trend_pct: number;
    series: { label: string; value: number }[];
  };
  distribution: {
    total: number;
    healthy: HealthTierBucket;
    attention: HealthTierBucket;
    at_risk: HealthTierBucket;
  };
  churn_risk: HealthChurnRiskItem[];
  module_utilization: HealthModuleUtilization[];
}

// ── Client Health list (Level 2) ─────────────────────────────────────────────

export interface HealthClientListItem {
  company_user_id: number;
  company: string;
  industry: string | null;
  plan: string | null;
  is_new: boolean;
  vehicles: number;
  users: number;
  active_users: number;
  modules_adopted: number;
  modules_applicable: number;
  trend: number[];
  health: number;
  tier: HealthTier;
}

export interface HealthClientsResponse {
  needs_compute: boolean;
  counts: { all: number; healthy: number; attention: number; at_risk: number };
  items: HealthClientListItem[];
  total: number;
  per_page: number;
  current_page: number;
  last_page: number;
}

// ── Client Profile (Level 3) ─────────────────────────────────────────────────

export interface HealthComponentScore {
  score: number;
  weight: number;
  included: boolean;
}

export type HealthBreakdown = Record<
  "activity" | "adoption" | "frequency" | "completeness" | "growth",
  HealthComponentScore
>;

export interface HealthAlert {
  key: string;
  severity: HealthAlertSeverity;
  message: string;
}

export interface HealthProfileHeader {
  company_user_id: number;
  company: string;
  industry: string | null;
  plan: string | null;
  client_since: string | null;
  is_new: boolean;
  health: number;
  tier: HealthTier;
  tiles: { vehicles: number; users: number; active: number; mau: number };
}

export interface HealthFleetMaturity {
  percent: number;
  items: { key: string; done: boolean }[];
}

export interface HealthOverview {
  breakdown: HealthBreakdown;
  adoption_alerts: HealthAlert[];
  engagement_trend: { current: number; previous: number; change_pct: number };
  fleet_maturity: HealthFleetMaturity;
}

export interface HealthMostActiveUser {
  user_id: number;
  name: string;
  count: number;
}

export interface HealthActivity {
  dau: number;
  wau: number;
  mau: number;
  logins_30d: number;
  avg_logins_per_user: number;
  most_active_users: HealthMostActiveUser[];
  inactive_users: { d30: number; d60: number; d90: number };
  /** 14-day DAU/WAU/MAU history for the card trend lines (empty until snapshots accumulate). */
  series: { dau: number[]; wau: number[]; mau: number[] };
}

export type HealthModuleStatus = "active" | "low" | "unused" | "n/a";

export interface HealthAdoptionModule {
  key: string;
  label: string;
  type: "flow" | "stock";
  scope: "per_vehicle" | "account" | "record";
  usage_pct: number;
  threshold: number;
  applicable: boolean;
  adopted: boolean;
  status: HealthModuleStatus;
  first_used: string | null;
}

export interface HealthDiscoveryEntry {
  month: string;
  modules: string[];
}

export interface HealthAdoption {
  modules: HealthAdoptionModule[];
  ranking: { key: string; label: string; usage_pct: number }[];
  discovery_timeline: HealthDiscoveryEntry[];
}

export interface HealthNavPath {
  path: string[];
  frequency: number;
}

export interface HealthHeatmap {
  by_hour: number[];
  by_weekday: number[];
  matrix: number[][];
}

export interface HealthAnnualActivity {
  count: number;
  days: { date: string; count: number }[];
}

export interface HealthBehavior {
  nav_paths: HealthNavPath[];
  avg_session_minutes: number;
  heatmap: HealthHeatmap;
  annual_activity: HealthAnnualActivity;
}

export interface HealthBenchmarkMetric {
  key: string;
  label: string;
  value: number;
  peer_avg: number;
  diff_pct: number;
}

export interface HealthBenchmark {
  available: boolean;
  peer_count?: number;
  below_peer_count: number;
  metrics: HealthBenchmarkMetric[];
}

export interface HealthClientProfile {
  header: HealthProfileHeader;
  overview: HealthOverview;
  activity: HealthActivity;
  adoption: HealthAdoption;
  behavior: HealthBehavior;
  benchmark: HealthBenchmark;
}

// ── Configuration ────────────────────────────────────────────────────────────

export interface HealthModuleMeta {
  key: string;
  label: string;
  type: "flow" | "stock";
  scope: "per_vehicle" | "account" | "record";
  unit: string;
}

export interface HealthWeights {
  activity: number;
  adoption: number;
  frequency: number;
  completeness: number;
  growth: number;
}

export interface HealthConfig {
  weights: HealthWeights;
  targets: { target_actions: number; target_logins: number };
  growth_band: number;
  module_thresholds: Record<string, number>;
  completeness_items: string[];
  tiers: { healthy: number; at_risk: number };
  alert_thresholds: Record<string, number>;
  default_period: HealthPeriod;
  modules: HealthModuleMeta[];
  defaults: Record<string, unknown>;
}

// The PUT body uses FLAT tier_*/target_* keys (GET nests them). The form maps between the two.
export interface UpdateHealthConfigPayload {
  weights?: HealthWeights;
  target_actions?: number;
  target_logins?: number;
  growth_band?: number;
  module_thresholds?: Record<string, number>;
  completeness_items?: string[];
  tier_healthy?: number;
  tier_at_risk?: number;
  alert_thresholds?: Record<string, number>;
  default_period?: HealthPeriod;
}
