export interface ValidationError {
  field: string;
  message: string;
}

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_REGEX = /^[0-9+\s().-]{8,20}$/;

export const validateBooking = (body: Record<string, unknown>): ValidationError[] => {
  const errors: ValidationError[] = [];

  const requiredFields: Record<string, string> = {
    treatment: 'Le soin sélectionné',
    date: 'La date',
    time: "L'heure",
    firstName: 'Le prénom',
    lastName: 'Le nom',
    email: "L'email",
    phone: 'Le téléphone',
  };

  for (const [field, label] of Object.entries(requiredFields)) {
    const value = body[field];
    if (typeof value !== 'string' || value.trim().length === 0) {
      errors.push({ field, message: `${label} est requis` });
    }
  }

  if (typeof body.email === 'string' && body.email.trim() && !EMAIL_REGEX.test(body.email)) {
    errors.push({ field: 'email', message: "Format d'email invalide" });
  }

  if (typeof body.phone === 'string' && body.phone.trim() && !PHONE_REGEX.test(body.phone)) {
    errors.push({ field: 'phone', message: 'Format de téléphone invalide' });
  }

  if (typeof body.date === 'string' && body.date.trim()) {
    const selectedDate = new Date(body.date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    if (selectedDate < today) {
      errors.push({ field: 'date', message: 'La date ne peut pas être dans le passé' });
    }
  }

  if (typeof body.message === 'string' && body.message.length > 1000) {
    errors.push({ field: 'message', message: 'Le message est trop long (max 1000 caractères)' });
  }

  return errors;
};

export const validateContact = (body: Record<string, unknown>): ValidationError[] => {
  const errors: ValidationError[] = [];

  const requiredFields: Record<string, string> = {
    firstName: 'Le prénom',
    lastName: 'Le nom',
    email: "L'email",
    message: 'Le message',
  };

  for (const [field, label] of Object.entries(requiredFields)) {
    const value = body[field];
    if (typeof value !== 'string' || value.trim().length === 0) {
      errors.push({ field, message: `${label} est requis` });
    }
  }

  if (typeof body.email === 'string' && body.email.trim() && !EMAIL_REGEX.test(body.email)) {
    errors.push({ field: 'email', message: "Format d'email invalide" });
  }

  if (typeof body.message === 'string' && body.message.trim().length < 10) {
    errors.push({ field: 'message', message: 'Le message doit contenir au moins 10 caractères' });
  }

  if (typeof body.message === 'string' && body.message.length > 2000) {
    errors.push({ field: 'message', message: 'Le message est trop long (max 2000 caractères)' });
  }

  return errors;
};