import type { Collaborator } from "./roles";
import type { PortfolioPrivilege } from "@/app/lib/portfolioAdmin";

export type CollaboratorsResponse = {
  users: Collaborator[];
  currentUser?: { privilege: PortfolioPrivilege };
};

// Shared fetcher used by every component that queries the portfolio user
// list. Keeping a single function (and a single response shape) means
// useQuery deduping behaves correctly when the user-access page mounts
// both UsersPermissionsCard and CapabilitiesCard against the same key.
export async function fetchCollaborators(
  portfolioId: string,
): Promise<CollaboratorsResponse> {
  const res = await fetch(`/api/portfolio/${portfolioId}/collaborators`);
  if (!res.ok) throw new Error("Failed to fetch collaborators");
  const json = await res.json();
  const rawUsers = Array.isArray(json) ? json : (json?.users ?? []);
  const users: Collaborator[] = Array.isArray(rawUsers)
    ? rawUsers.map((u: any) => ({
        portfolioUserId: String(u.portfolioUserId),
        userId: String(u.userId),
        name: u.name ?? null,
        email: u.email ?? "",
        role: u.role,
      }))
    : [];
  const privilege: PortfolioPrivilege | undefined =
    json?.currentUser?.privilege;
  return privilege ? { users, currentUser: { privilege } } : { users };
}

export const COLLABORATORS_QUERY_KEY = (portfolioId: string) =>
  ["portfolioUsers", portfolioId] as const;
