import { z } from 'zod';

export const EventHandlerTypeSchema = z.enum(['webhook', 'job', 'notification', 'sse']);
export const EventSubscriptionStatusSchema = z.enum(['active', 'paused', 'disabled']);

export const EventSubscriptionSchema = z.object({
  id: z.string().min(1),
  productId: z.string().min(1),
  topic: z.string().min(1),
  handlerType: EventHandlerTypeSchema,
  status: EventSubscriptionStatusSchema,
  config: z.record(z.unknown()).default({}),
  filterExpression: z.string().optional(),
  description: z.string().optional(),
  createdBy: z.string().min(1),
  createdAt: z.string(),
  updatedAt: z.string(),
});

export type EventSubscriptionDoc = z.infer<typeof EventSubscriptionSchema> & {
  _ts?: number;
  _etag?: string;
};

export const CreateEventSubscriptionSchema = z.object({
  topic: z.string().min(1),
  handlerType: EventHandlerTypeSchema,
  config: z.record(z.unknown()).default({}),
  filterExpression: z.string().optional(),
  description: z.string().optional(),
});

export type CreateEventSubscriptionInput = z.infer<typeof CreateEventSubscriptionSchema>;

export const UpdateEventSubscriptionSchema = z.object({
  status: EventSubscriptionStatusSchema.optional(),
  config: z.record(z.unknown()).optional(),
  filterExpression: z.string().optional(),
  description: z.string().optional(),
});

export type UpdateEventSubscriptionInput = z.infer<typeof UpdateEventSubscriptionSchema>;

export const ListEventSubscriptionsQuerySchema = z.object({
  topic: z.string().optional(),
  handlerType: EventHandlerTypeSchema.optional(),
  status: EventSubscriptionStatusSchema.optional(),
  limit: z.coerce.number().min(1).max(100).default(50),
});

export type ListEventSubscriptionsQuery = z.infer<typeof ListEventSubscriptionsQuerySchema>;

// ── Dead-Letter Queue ────────────────────────────────────────

export const DlqEntrySchema = z.object({
  id: z.string().min(1),
  productId: z.string().min(1),
  topic: z.string().min(1),
  payload: z.record(z.unknown()),
  error: z.string(),
  attempts: z.number().int().min(1),
  subscriptionId: z.string().optional(),
  originalEventId: z.string().optional(),
  createdAt: z.string(),
});

export type DlqEntryDoc = z.infer<typeof DlqEntrySchema> & {
  _ts?: number;
  _etag?: string;
};

export const ListDlqQuerySchema = z.object({
  topic: z.string().optional(),
  limit: z.coerce.number().min(1).max(100).default(50),
});

export type ListDlqQuery = z.infer<typeof ListDlqQuerySchema>;
