/**
 * fetchAllMembers
 *
 * Utilities for fetching ConnectWise member records and resolving
 * CW identifiers from email addresses.
 */

import { connectWiseApi, prisma } from "../../../constants";

export interface CWMember {
  id: number;
  identifier: string;
  firstName: string;
  lastName: string;
  officeEmail?: string | null;
  inactiveFlag: boolean;
  _info?: Record<string, any>;
}

/**
 * Fetch all active members from ConnectWise.
 */
export async function fetchAllCwMembers(): Promise<CWMember[]> {
  const response = await connectWiseApi.get<CWMember[]>(
    "/system/members?pageSize=1000&conditions=inactiveFlag=false"
  );
  return response.data ?? [];
}

/**
 * Resolve a ConnectWise member identifier given an email address.
 *
 * First checks the local database, then falls back to CW API.
 * Returns null when no match is found.
 */
export async function findCwIdentifierByEmail(
  email: string
): Promise<string | null> {
  const normalised = email.trim().toLowerCase();

  const local = await prisma.cwMember
    .findFirst({ where: { officeEmail: normalised } })
    .catch(() => null);

  if (local) return local.identifier;

  return null;
}
