import { z } from 'zod';

import { BINDABLE_PATHS } from '@/lib/templates/bindable-fields';

export const formFieldSchema = z.object({
  key: z.string().min(1).max(80),
  label: z.string().min(1).max(200),
  type: z.enum(['text', 'textarea', 'email', 'phone', 'number', 'select', 'checkbox']),
  required: z.boolean().optional().default(false),
  options: z.array(z.string()).optional(),
  helpText: z.string().optional(),
  /**
   * Optional binding to an Interest/Client/Yacht column. When set, the
   * supplemental-form runtime prefills the field from the linked entity
   * AND writes the submitted value back to that column on apply (with an
   * `interest_field_history` row capturing the override). Validated
   * against `BINDABLE_FIELDS` so unknown paths can't sneak in.
   */
  bindTo: z
    .string()
    .refine((v) => BINDABLE_PATHS.includes(v), {
      message: 'Unknown bindable path',
    })
    .optional(),
});

export const createFormTemplateSchema = z.object({
  name: z.string().min(1).max(200),
  description: z.string().optional(),
  fields: z.array(formFieldSchema).min(1, 'At least one field is required'),
  branding: z.record(z.string(), z.unknown()).optional(),
  isActive: z.boolean().optional().default(true),
});

export const updateFormTemplateSchema = createFormTemplateSchema.partial();

export type FormField = z.infer<typeof formFieldSchema>;
export type CreateFormTemplateInput = z.infer<typeof createFormTemplateSchema>;
export type UpdateFormTemplateInput = z.infer<typeof updateFormTemplateSchema>;
