/**
 * memberCache
 *
 * In-process Collection cache for ConnectWise member records.
 * Used to avoid repeated DB lookups when resolving member names.
 */

import { Collection } from "@discordjs/collection";
import { prisma } from "../../../constants";
import type { CWMember } from "./fetchAllMembers";

let _cache: Collection<string, CWMember> = new Collection();

/**
 * Replace the entire member cache with a new collection.
 */
export async function setMemberCache(
  members: Collection<string, CWMember>
): Promise<void> {
  _cache = members;
}

/**
 * Return the current member cache collection.
 */
export async function getMemberCache(): Promise<Collection<string, CWMember>> {
  return _cache;
}

/**
 * Resolve a display name from a member identifier.
 *
 * Returns "<firstName> <lastName>" when the member is found in the cache,
 * or the raw identifier string when not found / name parts are empty.
 */
export function resolveMemberName(identifier: string): string {
  const member = _cache.get(identifier);
  if (!member) return identifier;

  const full = `${member.firstName} ${member.lastName}`.trim();
  return full || identifier;
}

/**
 * Resolve a member identifier to a structured object containing
 * the member's name, CW member ID, and local user ID (if any).
 */
export async function resolveMember(identifier: string): Promise<{
  identifier: string;
  name: string;
  cwMemberId: number | null;
  id: string | null;
}> {
  const member = _cache.get(identifier);
  const name = resolveMemberName(identifier);
  const cwMemberId = member?.id ?? null;

  const localUser = await prisma.user
    .findFirst({ where: { cwIdentifier: identifier }, select: { id: true } })
    .catch(() => null);

  return {
    identifier,
    name,
    cwMemberId,
    id: localUser?.id ?? null,
  };
}
