import { z } from 'zod';

import { type MoodDurationPreset } from 'src/types/userMood';

import { DURATION_PRESETS } from './constants';

const DURATION_VALUES = DURATION_PRESETS.map(preset => preset.value) as [
  MoodDurationPreset,
  ...MoodDurationPreset[],
];

export const createMoodFormSchema = (t: (key: string) => string) =>
  z
    .object({
      emoji: z.string().min(1, t('general:required_field')),
      description: z.string().max(100),
      // Nullable to match `MoodFormValues.duration` (initial form state is
      // `null`). The non-null requirement is asserted in a refine below.
      duration: z.enum(DURATION_VALUES).nullable(),
      customDate: z.date().nullable(),
      customTime: z.date().nullable(),
    })
    .refine(values => values.duration != null, {
      path: ['duration'],
      message: t('general:required_field'),
    })
    .refine(
      values => values.duration !== 'custom' || values.customDate != null,
      {
        path: ['customDate'],
        message: t('general:required_field'),
      },
    )
    .refine(
      values => values.duration !== 'custom' || values.customTime != null,
      {
        path: ['customTime'],
        message: t('general:required_field'),
      },
    );
