import type { TenantSummary, UserSummary } from "../../lib/adminApi";

type UserAppointment = {
  tenantId?: string;
  tenantSlug?: string;
  grade?: string;
  jobTitle?: string;
  position?: string;
};

type TenantIdentity = Pick<TenantSummary, "id" | "slug">;

function normalizeText(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function getUserAppointments(user: UserSummary): UserAppointment[] {
  const rawAppointments = user.metadata?.additionalAppointments;
  if (!Array.isArray(rawAppointments)) return [];

  return rawAppointments
    .filter(
      (item): item is Record<string, unknown> =>
        typeof item === "object" && item !== null,
    )
    .map((item) => ({
      tenantId: normalizeText(item.tenantId),
      tenantSlug: normalizeText(item.tenantSlug),
      grade: normalizeText(item.grade),
      jobTitle: normalizeText(item.jobTitle),
      position: normalizeText(item.position),
    }));
}

export function getUserOrgProfile(user: UserSummary, tenant?: TenantIdentity) {
  const appointment = getUserAppointments(user).find((item) => {
    if (tenant?.id && item.tenantId === tenant.id) return true;
    if (
      tenant?.slug &&
      item.tenantSlug &&
      item.tenantSlug.toLowerCase() === tenant.slug.toLowerCase()
    ) {
      return true;
    }
    return false;
  });

  return {
    grade: appointment?.grade || normalizeText(user.grade),
    jobTitle: appointment?.jobTitle || normalizeText(user.jobTitle),
    position: appointment?.position || normalizeText(user.position),
  };
}

export function getOrgChartUserDisplayName(
  user: UserSummary,
  tenant?: TenantIdentity,
) {
  const { grade, jobTitle, position } = getUserOrgProfile(user, tenant);
  const baseName = user.name.trim();
  const detail = position || jobTitle;

  if (grade && detail) return `${baseName} ${grade}(${detail})`;
  if (grade) return `${baseName} ${grade}`;
  if (detail) return `${baseName}(${detail})`;
  return baseName;
}
