import { useGetIdentity } from "@refinedev/core";
import { useCallback } from "react";

export interface SchemeViewerIdentity {
  name?: string | null;
  username?: string | null;
}

export const resolveSchemeCreatorName = (
  schemeUsername: string | null | undefined,
  viewer: SchemeViewerIdentity | null | undefined,
) => {
  const username = schemeUsername?.trim();
  if (!username) return "-";

  const viewerUsername = viewer?.username?.trim();
  const viewerName = viewer?.name?.trim();
  return viewerUsername === username && viewerName ? viewerName : username;
};

export const useSchemeCreatorName = () => {
  const { data: viewer } = useGetIdentity<SchemeViewerIdentity>();

  return useCallback(
    (schemeUsername: string | null | undefined) =>
      resolveSchemeCreatorName(schemeUsername, viewer),
    [viewer],
  );
};
