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

/**
 * API validation schemas for notification endpoints.
 * Separate from domain types to enforce input validation at API boundary.
 */

/**
 * Notification category enum (matches database constraint)
 */
export const NotificationCategorySchema = z.enum(['info', 'queue', 'alert', 'error', 'system'])

/**
 * GET /api/notifications - Query parameters
 *
 * Security:
 * - limit: Max 100 to prevent DoS via excessive data transfer
 * - Default: 50 notifications
 * - Coerced from string to number (query params are always strings)
 */
export const GetNotificationsQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(50),
  offset: z.coerce.number().int().min(0).default(0)
})

/**
 * PATCH /api/notifications/:id/read - Path parameters
 *
 * Security:
 * - UUID validation prevents SQL injection attempts
 */
export const MarkAsReadParamsSchema = z.object({
  id: UuidSchema
})

/**
 * Internal: Create notification schema
 * Used by notification service/triggers, not exposed as API endpoint
 * (notifications are created by system only, not by users)
 *
 * Security:
 * - Strict mode: prevents mass assignment attacks
 * - UUID validation: ensures valid user/org IDs
 * - Length limits: prevents DoS via large payloads
 *   - Title: 200 chars (reasonable for notification headers)
 *   - Message: 1000 chars (detailed messages without DoS risk)
 * - URL validation: ensures actionUrl is valid URL if provided
 */
export const CreateNotificationSchema = z
  .object({
    userId: UuidSchema,
    organizationId: UuidSchema,
    category: NotificationCategorySchema,
    title: z.string().trim().min(1).max(200),
    message: z.string().trim().min(1).max(1000),
    actionUrl: z.string().url().optional()
  })
  .strict()

/**
 * PATCH /api/notifications/batch/read - Request body
 *
 * Security:
 * - Strict mode: prevents mass assignment attacks
 * - UUID array validation: ensures valid notification IDs
 * - Min 1 / Max 500: prevents empty no-op calls and oversized batches
 */
export const BatchMarkAsReadRequestSchema = z
  .object({
    ids: z.array(UuidSchema).min(1).max(500)
  })
  .strict()

/**
 * Bundled export (mirrors ProjectSchemas pattern)
 */
export const NotificationSchemas = {
  GetNotificationsQuery: GetNotificationsQuerySchema,
  MarkAsReadParams: MarkAsReadParamsSchema,
  CreateNotification: CreateNotificationSchema,
  BatchMarkAsReadRequest: BatchMarkAsReadRequestSchema
}

/**
 * Type exports for use in handlers
 */
export type GetNotificationsQuery = z.infer<typeof GetNotificationsQuerySchema>
export type MarkAsReadParams = z.infer<typeof MarkAsReadParamsSchema>
export type CreateNotificationInput = z.infer<typeof CreateNotificationSchema>
export type BatchMarkAsReadRequest = z.infer<typeof BatchMarkAsReadRequestSchema>
