import { z } from 'zod';

// Validation pour la date de naissance (doit être > 13 ans)
const validateAge = (birthdate: string | undefined): boolean => {
  if (!birthdate || birthdate.trim() === '') return true;

  const birth = new Date(birthdate);
  const today = new Date();
  const age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    return age - 1 >= 13;
  }

  return age >= 13;
};

export const profileSchema = z.object({
  first_name: z
    .string()
    .max(100, 'First name must be at most 100 characters')
    .optional()
    .or(z.literal('')),
  last_name: z
    .string()
    .max(100, 'Last name must be at most 100 characters')
    .optional()
    .or(z.literal('')),
  username: z
    .string()
    .min(3, 'Username must be at least 3 characters')
    .max(30, 'Username must be at most 30 characters')
    .regex(
      /^[a-zA-Z0-9_]+$/,
      'Username can only contain letters, numbers, and underscores',
    )
    .optional()
    .or(z.literal('')),
  bio: z
    .string()
    .max(500, 'Bio must be at most 500 characters')
    .optional()
    .or(z.literal('')),
  location: z
    .string()
    .max(100, 'Location must be at most 100 characters')
    .optional()
    .or(z.literal('')),
  birthdate: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'Invalid date format. Use YYYY-MM-DD')
    .optional()
    .or(z.literal(''))
    .refine((val) => !val || val === '' || validateAge(val), {
      message: 'User must be at least 13 years old',
    }),
  gender: z
    .enum(['Male', 'Female', 'Other', 'Prefer not to say'], {
      errorMap: () => ({ message: 'Invalid gender value' }),
    })
    .optional(),
});

export type ProfileFormData = z.infer<typeof profileSchema>;
