import type { Locale } from '@/lib/i18n';
import { type z } from 'zod';

const ZOD_MESSAGES = {
  he: {
    required: 'שדה חובה',
    invalid_type: 'ערך לא חוקי',
    too_small_string: 'ערך קצר מדי',
    too_big_string: 'ערך ארוך מדי',
    too_small_number: 'הערך קטן מהמינימום המותר',
    too_big_number: 'הערך גדול מהמקסימום המותר',
    invalid_string_email: 'כתובת דואר אלקטרוני לא חוקית',
    invalid_string_url: 'כתובת URL לא חוקית',
    invalid_enum_value: 'ערך לא מורשה',
    invalid_date: 'תאריך לא חוקי',
    custom: 'קלט לא חוקי',
  },
  en: {
    required: 'Required',
    invalid_type: 'Invalid value',
    too_small_string: 'Too short',
    too_big_string: 'Too long',
    too_small_number: 'Below minimum',
    too_big_number: 'Above maximum',
    invalid_string_email: 'Invalid email address',
    invalid_string_url: 'Invalid URL',
    invalid_enum_value: 'Invalid option',
    invalid_date: 'Invalid date',
    custom: 'Invalid input',
  },
} as const satisfies Record<Locale, Record<string, string>>;

type MsgKey = keyof (typeof ZOD_MESSAGES)['he'];

export function createZodErrorMap(locale: Locale): z.ZodErrorMap {
  const msgs = ZOD_MESSAGES[locale];
  const m = (key: MsgKey): string => msgs[key];
  return (issue) => {
    switch (issue.code) {
      case 'invalid_type':
        if (issue.input === undefined) return { message: m('required') };
        if (issue.expected === 'date') return { message: m('invalid_date') };
        return { message: m('invalid_type') };
      case 'too_small':
        return {
          message: issue.origin === 'string' ? m('too_small_string') : m('too_small_number'),
        };
      case 'too_big':
        return {
          message: issue.origin === 'string' ? m('too_big_string') : m('too_big_number'),
        };
      case 'invalid_format': {
        const format = (issue as { format?: string }).format;
        if (format === 'email') return { message: m('invalid_string_email') };
        if (format === 'url') return { message: m('invalid_string_url') };
        return { message: m('invalid_type') };
      }
      case 'invalid_value':
        return { message: m('invalid_enum_value') };
      case 'custom':
        return { message: m('custom') };
      default:
        return undefined;
    }
  };
}
