import {
  getCampusId,
  getOrganizationId,
  hasGlobalAccess,
} from '@/services/shared/access';
import type { CurrentUser } from '@/db/api/types';

/**
 * Pure audio-library visibility/management rules (Workstream 13), separated from
 * the data layer so they are unit-testable. The `audio_files` query in
 * `services/audio_files.ts` mirrors {@link isAudioVisibleTo}.
 */
export interface AudioScope {
  readonly organizationId: string | null;
  readonly campusId: string | null;
}

/**
 * A row is visible when it is a **global default** (`organizationId` null), or it
 * belongs to the caller's organization and is either campus-wide (`campusId`
 * null) or on the caller's campus. Global-access users see everything.
 */
export function isAudioVisibleTo(
  record: AudioScope,
  currentUser?: CurrentUser,
): boolean {
  if (hasGlobalAccess(currentUser)) {
    return true;
  }
  if (record.organizationId == null) {
    return true;
  }
  if (record.organizationId !== getOrganizationId(currentUser)) {
    return false;
  }
  return record.campusId == null || record.campusId === getCampusId(currentUser);
}

/**
 * Only global-access users may manage global defaults; everyone else may manage
 * only their own organization's uploads (never a global default).
 */
export function canManageAudioFile(
  record: AudioScope,
  currentUser?: CurrentUser,
): boolean {
  if (hasGlobalAccess(currentUser)) {
    return true;
  }
  if (record.organizationId == null) {
    return false;
  }
  return record.organizationId === getOrganizationId(currentUser);
}
