import { z } from 'zod'
import { UuidSchema, NonEmptyStringSchema, PaginationSchema } from '../../platform/utils/validation'

/**
 * Webhook Endpoint API Validation Schemas
 *
 * HTTP request/response validation for the webhook endpoints CRUD API.
 * These schemas are browser-safe and shared between API and frontend.
 *
 * Design notes:
 * - Request schemas use `.strict()` to reject unknown fields (mass assignment prevention)
 * - Response schemas do NOT use `.strict()` (allows forward-compatible additions)
 * - Update schema requires at least one field via `.refine()`
 */

/**
 * Status enum for webhook endpoints
 */
export const WebhookEndpointStatusSchema = z.enum(['active', 'paused'])

/**
 * POST /api/webhook-endpoints - Create a new webhook endpoint
 *
 * The `key` and `id` are generated server-side and not accepted in the request.
 */
export const CreateWebhookEndpointRequestSchema = z
  .object({
    /** User-facing label for the endpoint */
    name: NonEmptyStringSchema,
    /** Target workflow resourceId to invoke on inbound requests (can be set later) */
    resourceId: NonEmptyStringSchema.optional(),
    /** Optional description */
    description: z.string().optional()
  })
  .strict()

export type CreateWebhookEndpointRequest = z.infer<typeof CreateWebhookEndpointRequestSchema>

/**
 * PATCH /api/webhook-endpoints/:id - Update an existing webhook endpoint
 *
 * At least one field must be provided.
 */
export const UpdateWebhookEndpointRequestSchema = z
  .object({
    name: NonEmptyStringSchema.optional(),
    description: z.string().optional(),
    resourceId: NonEmptyStringSchema.optional(),
    status: WebhookEndpointStatusSchema.optional()
  })
  .strict()
  .refine(
    (data) =>
      data.name !== undefined ||
      data.description !== undefined ||
      data.resourceId !== undefined ||
      data.status !== undefined,
    { message: 'At least one field (name, description, resourceId, or status) must be provided' }
  )

export type UpdateWebhookEndpointRequest = z.infer<typeof UpdateWebhookEndpointRequestSchema>

/**
 * Response shape for a single webhook endpoint.
 * NOT strict — response schemas allow extra fields for forward compatibility.
 */
export const WebhookEndpointResponseSchema = z.object({
  id: UuidSchema,
  organizationId: UuidSchema,
  key: z.string().optional(),
  keyPrefix: z.string().nullable(),
  name: z.string(),
  description: z.string().nullable(),
  resourceId: z.string().nullable(),
  status: WebhookEndpointStatusSchema,
  lastTriggeredAt: z.string().datetime().nullable(),
  requestCount: z.number().int().min(0),
  createdAt: z.string().datetime(),
  updatedAt: z.string().datetime()
})

export type WebhookEndpointResponse = z.infer<typeof WebhookEndpointResponseSchema>

/**
 * GET /api/webhook-endpoints - List webhook endpoints query params
 *
 * Extends standard pagination with optional status filter.
 */
export const ListWebhookEndpointsQuerySchema = PaginationSchema.extend({
  status: WebhookEndpointStatusSchema.optional()
})

export type ListWebhookEndpointsQuery = z.infer<typeof ListWebhookEndpointsQuerySchema>

/**
 * Named collection of all webhook endpoint schemas for route registration
 */
export const WebhookEndpointSchemas = {
  CreateRequest: CreateWebhookEndpointRequestSchema,
  UpdateRequest: UpdateWebhookEndpointRequestSchema,
  Response: WebhookEndpointResponseSchema,
  ListQuery: ListWebhookEndpointsQuerySchema
}
