// Directory Sync: read members / departments from CSM. No mirror table — we call
// CSM directly and keep a short in-memory (RAM) cache to smooth repeated reads.
import { csmGet, unwrap } from './client';
import { CSM } from './config';

type CacheEntry = { at: number; data: any[] };
const cache = new Map<string, CacheEntry>();

function getCached(key: string): any[] | null {
  const e = cache.get(key);
  if (e && Date.now() - e.at < CSM.dirCacheMs()) return e.data;
  return null;
}
function setCached(key: string, data: any[]): void {
  cache.set(key, { at: Date.now(), data });
}

/** Invalidate the whole directory cache (e.g. for a manual refresh endpoint). */
export function clearCsmDirectoryCache(): void {
  cache.clear();
}

export async function getCsmDepartments(): Promise<any[]> {
  const cached = getCached('departments');
  if (cached) return cached;
  const data = unwrap(await csmGet('/departments'));
  const arr = Array.isArray(data) ? data : [];
  setCached('departments', arr);
  return arr;
}

export interface CsmMemberQuery {
  ids?: string[];
  status?: string; // 'Active' (default on CSM) | 'all'
  /** Only members granted access to THIS webtool (AOM), each incl. webtool.roles. */
  granted?: boolean;
}

/** Resolve a set of CSM user ids -> {name,email} for display (plan §9.5). */
export async function resolveCsmUserNames(ids: Array<string | undefined | null>): Promise<Map<string, { name?: string; email?: string }>> {
  const uniq = [...new Set(ids.filter(Boolean).map((v) => String(v)))];
  const map = new Map<string, { name?: string; email?: string }>();
  if (!uniq.length) return map;
  const members = await getCsmMembers({ ids: uniq, status: 'all' });
  for (const m of members) map.set(String(m.id), { name: m.name, email: m.email });
  return map;
}

export async function getCsmMembers(opts: CsmMemberQuery = {}): Promise<any[]> {
  const params = new URLSearchParams();
  if (opts.ids && opts.ids.length) params.set('ids', opts.ids.join(','));
  if (opts.status) params.set('status', opts.status);
  if (opts.granted) params.set('granted', 'true');
  const qs = params.toString();

  // Cache only the broad lists (no ids). id-lookups are narrow/varied — skip cache.
  const cacheable = !(opts.ids && opts.ids.length);
  const cacheKey = `members?${qs}`;
  if (cacheable) {
    const cached = getCached(cacheKey);
    if (cached) return cached;
  }

  const data = unwrap(await csmGet(`/members${qs ? `?${qs}` : ''}`));
  const arr = Array.isArray(data) ? data : [];
  if (cacheable) setCached(cacheKey, arr);
  return arr;
}
