export const RELATION_ID_MAP: Record<string, { key: string; path: string }> = {
  siteId: { key: 'site', path: 'sites' },
  machineId: { key: 'machine', path: 'machines' },
  composantId: { key: 'composant', path: 'composants' },
  pieceId: { key: 'piece', path: 'pieces' },
  productId: { key: 'product', path: 'products' },
  typeComposantId: { key: 'typeComposant', path: 'model_types' },
  typePieceId: { key: 'typePiece', path: 'model_types' },
  typeProductId: { key: 'typeProduct', path: 'model_types' },
};

export const toIri = (path: string, id: string): string => `/api/${path}/${id}`;

export const extractRelationId = (value: unknown): string | null => {
  if (!value) {
    return null;
  }
  if (typeof value === 'string') {
    const trimmed = value.trim();
    if (!trimmed) {
      return null;
    }
    if (trimmed.includes('/')) {
      const parts = trimmed.split('/').filter(Boolean);
      return parts.length ? (parts[parts.length - 1] ?? null) : null;
    }
    return trimmed;
  }
  if (typeof value === 'object' && 'id' in (value as Record<string, any>)) {
    const id = (value as Record<string, any>).id;
    return typeof id === 'string' ? id : null;
  }
  return null;
};

export const normalizeRelationIds = <T extends Record<string, any>>(payload: T): T => {
  if (!payload || typeof payload !== 'object') {
    return payload;
  }

  const next: Record<string, any> = { ...payload };
  Object.entries(RELATION_ID_MAP).forEach(([sourceKey, config]) => {
    const raw = next[sourceKey];
    if (typeof raw !== 'string') {
      return;
    }
    const trimmed = raw.trim();
    if (!trimmed) {
      return;
    }
    next[config.key] = toIri(config.path, trimmed);
    delete next[sourceKey];
  });

  return next as T;
};
