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

type UserAppointment = {
  tenantId?: string;
  tenantSlug?: string;
  isAdmin?: boolean;
  isManager?: boolean;
  isOwner?: boolean;
  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),
      isAdmin: item.isAdmin === true,
      isManager: item.isManager === true,
      isOwner: item.isOwner === true,
      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),
    isHighlighted:
      appointment?.isAdmin === true ||
      appointment?.isManager === true ||
      appointment?.isOwner === true,
    jobTitle: appointment?.jobTitle || normalizeText(user.jobTitle),
    position: appointment?.position || normalizeText(user.position),
  };
}

export function getOrgChartUserDisplayName(
  user: UserSummary,
  tenant?: TenantIdentity,
) {
  const { grade } = getUserOrgProfile(user, tenant);
  const baseName = user.name.trim();
  const displayGrade = getOrgRankDisplayName(grade);

  let displayName = baseName;
  if (displayGrade) displayName = `${baseName} ${displayGrade}`;
  return displayName;
}
