export interface StageChangeNotification {
  kind: 'stage_change';
  accountId: string;
  dealId: string;
  dealSide: 'demand' | 'supply';
  dealName: string;
  fromStage: string;
  toStage: string;
  changedAt: string;
}

export interface IdleCapacityNotification {
  kind: 'idle_capacity';
  accountId: string;
  commitmentId: string;
  commitmentName: string;
  gpuType: string;
  idleGpuHours: number;
  idleCostCents: number;
  utilisation: number;
  observedAt: string;
}

export type Notification = StageChangeNotification | IdleCapacityNotification;

export const NOTIFIER_PROVIDERS = ['slack', 'buzz'] as const;
export type NotifierProvider = (typeof NOTIFIER_PROVIDERS)[number];

export function isNotifierProvider(value: string): value is NotifierProvider {
  return (NOTIFIER_PROVIDERS as readonly string[]).includes(value);
}

export interface NotificationEnvelope {
  idempotencyKey: string;
  destination: string;
  workspaceId?: string | null;
  notification: Notification;
}

export interface NotificationReceipt {
  externalId: string | null;
}

/** Provider adapters perform one attempt; the durable worker owns retries. */
export interface Notifier {
  readonly provider: string;
  send(envelope: NotificationEnvelope, signal?: AbortSignal): Promise<NotificationReceipt>;
}

export class NotificationDeliveryError extends Error {
  constructor(
    readonly code: string,
    readonly retryable: boolean,
    readonly retryAfterMs?: number,
  ) {
    super(`Notification delivery failed (${code}).`);
    this.name = 'NotificationDeliveryError';
  }
}
