export const generateLogicalId = (id) => {
  const str = String(id).replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
  return 'CLI-' + str.substring(0, 6).padStart(6, '0');
};

export function toClient(raw) {
  const p = raw.payload ?? raw;
  const id = p.id ?? raw.id;
  const logicalId = generateLogicalId(id);
  return {
    id,
    logicalId,
    clientId: logicalId,
    name: p.first_name ? `${p.first_name} ${p.last_name || ''}`.trim() : (p.name || '—'),
    email: p.email || '',
    phone: p.phone || '',
    city: p.city || '',
    businessState: p.businessState || '',
    businessType: p.businessType || '',
    status: p.status || 'unknown',
    parcelVolume: Number(p.parcelVolume) || 0,
    activeContracts: Number(p.activeContracts) || 0,
    frequency: p.frequency || '',
    provider: p.provider || '',
    efficiency: p.efficiency || '',
    logisticsSegment: p.logisticsSegment || '',
    transitFrom: p.transitFrom || '',
    transitTo: p.transitTo || '',
    neighbourhood: p.neighbourhood || p.surveyZone || '',
    surveyAddress: p.surveyAddress || p.address || '',
    surveyLat: p.survey_lat ?? p.surveyLat ?? '',
    surveyLng: p.survey_long ?? p.surveyLng ?? '',
    dataConsent: p.dataConsent || '',
    lastUpdated: p.lastUpdated || '',
    pincode: p.pincode || p.postal_code || '',
    notes: p.notes || ''
  };
}

export function toUser(raw) {
  const p = raw.payload ?? raw;
  const id = p.id ?? raw.id;
  return {
    id,
    name: p.first_name ? `${p.first_name} ${p.last_name || ''}`.trim() : (p.name || '—'),
    email: p.email || '',
    phone: p.phone || '',
    role: p.role || 'unknown',
    pin: p.pin || ''
  };
}
