export interface CandidateFilters {
  // Basic fields
  firstName?: string;
  lastName?: string;
  email?: string;
  phone?: string;

  // Location fields
  postalCode?: string;
  city?: string;
  department?: string;

  // Candidate specific fields
  age?: number;
  ageMin?: number;
  ageMax?: number;

  applicationDateFrom?: string;
  applicationDateTo?: string;
  rdvDateFrom?: string;
  rdvDateTo?: string;

  status?: string;
  type?: string;
  sourceCandidate?: string;

  drivingLicenseDuration?: string;
  dureePermisMin?: number;
  dureePermisMax?: number;

  circuitProximity?: string;
  callFollowUp?: string;
  callBackDateFrom?: string;
  callBackDateTo?: string;

  q?: string;
}

export const mapFiltersToBackend = (
  frontendFilters: Record<string, { value: string; condition: string }>
): CandidateFilters => {
  const backendFilters: CandidateFilters = {};

  Object.entries(frontendFilters).forEach(([key, filter]) => {
    if (!filter.value || filter.value.trim() === '') return;

    const value = filter.value.trim();

    switch (key) {
      case 'nom':
        // ✅ CORRECTION: Gérer les noms complets (nom + prénom) ou un seul mot en cherchant dans les deux champs
        const nameParts = value.split(' ').filter(part => part.trim() !== '');
        if (nameParts.length >= 2) {
          // Si on a au moins 2 parties, la première est le nom de famille, le reste est le prénom
          backendFilters.lastName = nameParts[0];
          backendFilters.firstName = nameParts.slice(1).join(' ');
        } else if (nameParts.length === 1) {
          // Si une seule partie, chercher dans firstName ET lastName (le backend gérera l'OR)
          backendFilters.firstName = nameParts[0];
          backendFilters.lastName = nameParts[0];
        }
        // Si aucune partie (chaîne vide), les filtres firstName et lastName resteront vides
        break;

      case 'prenom':
        // Pour le prénom, on cherche dans firstName
        backendFilters.firstName = value;
        break;

      case 'email':
        backendFilters.email = value;
        break;

      case 'telephone':
        backendFilters.phone = value;
        break;

      case 'codePostal':
        backendFilters.postalCode = value;
        break;

      case 'ville':
        backendFilters.city = value;
        break;

      case 'departement':
        backendFilters.department = value;
        break;

      case 'age':
        const ageNum = parseInt(value);
        if (!isNaN(ageNum)) {
          if (filter.condition === 'gte') {
            backendFilters.ageMin = ageNum;
          } else if (filter.condition === 'lte') {
            backendFilters.ageMax = ageNum;
          } else {
            backendFilters.age = ageNum;
          }
        }
        break;

      case 'dureePermis':
        const permisNum = parseInt(value);
        if (!isNaN(permisNum)) {
          if (filter.condition === 'gte') {
            backendFilters.dureePermisMin = permisNum;
          } else if (filter.condition === 'lte') {
            backendFilters.dureePermisMax = permisNum;
          } else {
            backendFilters.drivingLicenseDuration = value;
          }
        } else {
          backendFilters.drivingLicenseDuration = value;
        }
        break;

      case 'sourceCandidat':
        // Convertir la valeur frontend vers l'enum backend
        const sourceMapping: Record<string, string> = {
          'Indeed': 'INDEED',
          'LinkedIn': 'LINKEDIN', 
          'Pôle emploi': 'POLE_EMPLOI',
          'Site web': 'SITE_WEB',
          'APEC': 'APEC',
          'Candidature spontanée': 'SPONTANEE',
          'Welcome to the Jungle': 'WELCOME_TO_THE_JUNGLE',
          'Autre': 'AUTRE'
        };
        backendFilters.sourceCandidate = sourceMapping[value] || value.toUpperCase();
        break;

      case 'proximiteCircuit':
        backendFilters.circuitProximity = value;
        break;

      case 'suiviAppel':
        backendFilters.callFollowUp = value;
        break;

      case 'dateCandidature':
        if (filter.condition === 'gte') {
          backendFilters.applicationDateFrom = value;
        } else if (filter.condition === 'lte') {
          backendFilters.applicationDateTo = value;
        }
        break;

      case 'dateHeureRdvAgence':
        if (filter.condition === 'gte') {
          backendFilters.rdvDateFrom = value;
        } else if (filter.condition === 'lte') {
          backendFilters.rdvDateTo = value;
        }
        break;

      case 'dateAppelRappel':
        // ✅ CORRECTION: Mapping pour la date d'appel/rappel
        if (filter.condition === 'gte') {
          backendFilters.callBackDateFrom = value;
        } else if (filter.condition === 'lte') {
          backendFilters.callBackDateTo = value;
        } else {
          // Si pas de condition spécifique, utiliser la date exacte
          backendFilters.callBackDateFrom = value;
          backendFilters.callBackDateTo = value;
        }
        break;

      default:
        if (!backendFilters.q) {
          backendFilters.q = value;
        } else {
          backendFilters.q += ` ${value}`;
        }
        break;
    }
  });

  return backendFilters;
};
