/**
 * Spend Alerts — proactive billing alerts admins configure on /spending.
 *
 * Wire types shared between client (RTK Query slice in reduxApi/billing) and
 * server (/v1/billing/spend-alerts controller). The DB stores `thresholds`
 * and `recipients` as JSONB blobs whose shape matches these types exactly —
 * see migration 1778896201000-create-spend-alert-table.
 */

export type SpendAlertType = 'org_spend' | 'per_user_spend' | 'overage_spend' | 'refill_spend';

/**
 * Unit identifier stored in `threshold.unit`. The client-side modal maps
 * these to human labels (% of monthly usage / credits used / etc.); the
 * server treats them opaquely for v1 (no evaluation yet).
 *
 * Adding a new unit requires an update here AND on the server-side enum
 * in `validateThresholdUnit` so persistence rejects unknown values rather
 * than silently storing them.
 */
export type SpendAlertThresholdUnit =
  // Org spend
  | 'percent'
  | 'credits_used'
  | 'dollars_spent'
  // Per-user spend
  | 'credits'
  | 'dollars'
  // Overage spend
  | 'overage_credits'
  | 'overage_dollars'
  // Refill spend. Credit-denominated — every refill-eligible plan
  // (TEAMS / POC) is credit-based, so there's no dollar variant.
  | 'refill_credits';

export interface SpendAlertThreshold {
  /** Positive number. Server validates this is > 0. */
  value: number;
  unit: SpendAlertThresholdUnit;
}

export type SpendAlertRecipientKind =
  /** Everyone with admin role on the org. Resolved at dispatch time. */
  | 'all_admins'
  /**
   * Per-user alerts only. The user whose usage crossed the threshold.
   * Resolved at dispatch time — not stored as a user_id, since the
   * recipient depends on which user fired the alert.
   */
  | 'triggering_user'
  /** Specific user by id. Resolved against the user table at dispatch. */
  | 'user';

export interface SpendAlertRecipient {
  kind: SpendAlertRecipientKind;
  /** Required when kind === 'user'. Ignored for other kinds. */
  userId?: string;
}

export interface SpendAlertDto {
  id: string;
  organizationId: string;
  alertType: SpendAlertType;
  thresholds: SpendAlertThreshold[];
  recipients: SpendAlertRecipient[];
  created: string;
  updated: string;
}

export interface CreateSpendAlertBody {
  alertType: SpendAlertType;
  thresholds: SpendAlertThreshold[];
  recipients: SpendAlertRecipient[];
}

export type UpdateSpendAlertBody = Partial<Pick<CreateSpendAlertBody, 'thresholds' | 'recipients'>>;

export interface ListSpendAlertsResponseBody {
  alerts: SpendAlertDto[];
}

export interface SpendAlertResponseBody {
  alert: SpendAlertDto;
}
