import { z } from 'zod';

const customQuestionSchema = z.object({
  id: z.string(),
  label: z.string(),
  type: z.enum(['text', 'select', 'checkbox']),
  required: z.boolean().optional(),
  options: z.array(z.string()).optional(),
});

/** Empty / whitespace → null so optional branding fields never fail validation. */
const optionalHttpUrl = z.preprocess((value) => {
  if (value === undefined || value === null) return null;
  if (typeof value !== 'string') return value;
  const trimmed = value.trim();
  return trimmed === '' ? null : trimmed;
}, z.string().url().nullable());

const optionalTagline = z.preprocess((value) => {
  if (value === undefined || value === null) return null;
  if (typeof value !== 'string') return value;
  const trimmed = value.trim();
  return trimmed === '' ? null : trimmed;
}, z.string().max(255).nullable());

/** Empty / whitespace → null for optional free-text fields. */
const optionalLocation = z.preprocess((value) => {
  if (value === undefined || value === null) return null;
  if (typeof value !== 'string') return value;
  const trimmed = value.trim();
  return trimmed === '' ? null : trimmed;
}, z.string().max(512).nullable());

const optionalMeetingUrl = z.preprocess((value) => {
  if (value === undefined || value === null) return null;
  if (typeof value !== 'string') return value;
  const trimmed = value.trim();
  return trimmed === '' ? null : trimmed;
}, z.string().url().max(2048).nullable());

export const createEventTypeSchema = z.object({
  slug: z.string().regex(/^[a-z0-9-]+$/).max(64),
  title: z.string().min(1).max(255),
  durationMinutes: z.coerce.number().int().min(1),
  bufferBeforeMinutes: z.coerce.number().int().min(0).default(0),
  bufferAfterMinutes: z.coerce.number().int().min(0).default(0),
  location: optionalLocation.optional(),
  meetingUrl: optionalMeetingUrl.optional(),
  description: z.string().optional(),
  customQuestions: z.array(customQuestionSchema).default([]),
  color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional(),
  bannerUrl: optionalHttpUrl.optional(),
  logoUrl: optionalHttpUrl.optional(),
  tagline: optionalTagline.optional(),
});

export const updateEventTypeSchema = createEventTypeSchema.partial();
