import { z } from 'zod'
import type { FormField, FormSchema } from './types'

/**
 * Zod validation schemas for form types
 * Provides runtime validation for form fields and schemas
 */

/**
 * Form field schema validation
 */
export const FormFieldSchema = z
  .object({
    name: z.string().min(1, 'Field name is required'),
    label: z.string().min(1, 'Field label is required'),
    type: z.enum(['text', 'textarea', 'number', 'select', 'checkbox', 'radio', 'richtext']),
    defaultValue: z.unknown().optional(),
    required: z.boolean().optional(),
    placeholder: z.string().optional(),
    description: z.string().optional(),
    options: z
      .array(
        z.object({
          label: z.string().min(1, 'Option label is required'),
          value: z.union([z.string(), z.number()])
        })
      )
      .optional(),
    min: z.number().optional(),
    max: z.number().optional(),
    defaultValueFromContext: z.string().optional()
  })
  .refine(
    (field) => {
      // Validate that select/radio fields have options
      if ((field.type === 'select' || field.type === 'radio') && (!field.options || field.options.length === 0)) {
        return false
      }
      return true
    },
    {
      message: 'Select and radio fields must have at least one option'
    }
  )

/**
 * Form schema validation
 */
export const FormSchemaSchema = z.object({
  title: z.string().optional(),
  description: z.string().optional(),
  fields: z.array(FormFieldSchema).min(1, 'Form must have at least one field')
})

/**
 * Validates a form schema
 * @throws ZodError if validation fails
 */
export function validateFormSchema(form: unknown): FormSchema {
  return FormSchemaSchema.parse(form)
}

/**
 * Validates a form field
 * @throws ZodError if validation fails
 */
export function validateFormField(field: unknown): FormField {
  return FormFieldSchema.parse(field)
}
