import { z } from 'zod';

// ── Webhook Events ──────────────────────────────────────────

export const WEBHOOK_EVENTS = [
  'user.created',
  'user.deleted',
  'subscription.created',
  'subscription.changed',
  'subscription.canceled',
  'payment.succeeded',
  'payment.failed',
  'invitation.redeemed',
  'referral.completed',
  'waitlist.joined',
  'flag.toggled',
  'flag.created',
  'flag.updated',
  'flag.deleted',
  'flag.kill_switch',
  'license.activated',
  'license.expired',
] as const;

export type WebhookEventType = (typeof WEBHOOK_EVENTS)[number];

// ── Subscription ────────────────────────────────────────────

export interface WebhookSubscriptionDoc {
  id: string;
  productId: string;
  url: string;
  secret: string;
  events: WebhookEventType[];
  enabled: boolean;
  failureCount: number;
  lastDeliveryAt?: string;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

export const CreateWebhookSubscriptionSchema = z.object({
  url: z.string().url(),
  events: z.array(z.enum(WEBHOOK_EVENTS)).min(1),
  productId: z.string().min(1),
});

export const UpdateWebhookSubscriptionSchema = z.object({
  url: z.string().url().optional(),
  events: z.array(z.enum(WEBHOOK_EVENTS)).min(1).optional(),
  enabled: z.boolean().optional(),
});

export type CreateWebhookSubscriptionInput = z.infer<typeof CreateWebhookSubscriptionSchema>;
export type UpdateWebhookSubscriptionInput = z.infer<typeof UpdateWebhookSubscriptionSchema>;

// ── Delivery ────────────────────────────────────────────────

export type WebhookDeliveryStatus = 'success' | 'failed' | 'retrying';

export interface WebhookDeliveryAttempt {
  attemptNumber: number;
  responseCode?: number;
  durationMs: number;
  error?: string;
  attemptedAt: string;
}

export interface WebhookDeliveryDoc {
  id: string;
  subscriptionId: string;
  pk: string;
  event: WebhookEventType;
  payload: Record<string, unknown>;
  status: WebhookDeliveryStatus;
  attempts: WebhookDeliveryAttempt[];
  createdAt: string;
  completedAt?: string;
  _ts?: number;
}

// ── Webhook Payload (outbound) ──────────────────────────────

export interface WebhookOutboundPayload {
  id: string;
  event: WebhookEventType;
  productId: string;
  timestamp: string;
  data: Record<string, unknown>;
}
