/**
 * Shared TypeScript interfaces and types for the Webhook / Event Streaming subsystem.
 * Imported by WebhookService, WebhookDeliveryWorker, EventPublisher, and their controllers.
 */

// ============================================================================
// Event Types
// ============================================================================

/** All event type identifiers that can be published and subscribed to. */
export type WebhookEventType =
  | 'agent.created'
  | 'agent.updated'
  | 'agent.suspended'
  | 'agent.reactivated'
  | 'agent.decommissioned'
  | 'credential.generated'
  | 'credential.rotated'
  | 'credential.revoked'
  | 'token.issued'
  | 'token.revoked';

// ============================================================================
// Webhook Subscription
// ============================================================================

/** A registered webhook subscription (secret fields are never included). */
export interface IWebhookSubscription {
  id: string;
  organization_id: string;
  name: string;
  url: string;
  events: WebhookEventType[];
  active: boolean;
  failure_count: number;
  created_at: Date;
  updated_at: Date;
}

/** Request body for creating a new webhook subscription. */
export interface ICreateWebhookRequest {
  name: string;
  url: string;
  events: WebhookEventType[];
}

/** Request body for partially updating a webhook subscription. */
export interface IUpdateWebhookRequest {
  name?: string;
  url?: string;
  events?: WebhookEventType[];
  active?: boolean;
}

// ============================================================================
// Webhook Delivery
// ============================================================================

/** A single webhook delivery attempt record. */
export interface IWebhookDelivery {
  id: string;
  subscription_id: string;
  event_type: WebhookEventType;
  payload: Record<string, unknown>;
  status: 'pending' | 'delivered' | 'failed' | 'dead_letter';
  http_status_code: number | null;
  attempt_count: number;
  next_retry_at: Date | null;
  delivered_at: Date | null;
  created_at: Date;
  updated_at: Date;
}

/** The envelope sent in every outbound webhook HTTP request body. */
export interface IWebhookPayload {
  /** UUID uniquely identifying this event occurrence. */
  id: string;
  /** The event type identifier. */
  event: WebhookEventType;
  /** ISO 8601 timestamp of when the event was published. */
  timestamp: string;
  /** The organization that owns the resource that changed. */
  organization_id: string;
  /** Event-specific data. Contents vary by event type. */
  data: Record<string, unknown>;
}

/** Paginated response for listing webhook deliveries. */
export interface IPaginatedDeliveriesResponse {
  deliveries: IWebhookDelivery[];
  total: number;
  limit: number;
  offset: number;
}
