import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
  canManageAudioFile,
  isAudioVisibleTo,
} from '@/services/shared/audio-access';
import type { CurrentUser } from '@/db/api/types';

const globalUser: CurrentUser = {
  id: 'sys',
  app_role: { globalAccess: true },
};
const campusUser: CurrentUser = {
  id: 'u1',
  organizationId: 'org1',
  campusId: 'campusA',
};

const globalDefault = { organizationId: null, campusId: null };
const orgWide = { organizationId: 'org1', campusId: null };
const sameCampus = { organizationId: 'org1', campusId: 'campusA' };
const otherCampus = { organizationId: 'org1', campusId: 'campusB' };
const otherOrg = { organizationId: 'org2', campusId: 'campusA' };

// --- visibility (Workstream 13) ---

test('global defaults are visible to everyone', () => {
  assert.equal(isAudioVisibleTo(globalDefault, campusUser), true);
});

test('a campus user sees own-org campus-wide and same-campus audio', () => {
  assert.equal(isAudioVisibleTo(orgWide, campusUser), true);
  assert.equal(isAudioVisibleTo(sameCampus, campusUser), true);
});

test('a campus user cannot see another campus or another org', () => {
  assert.equal(isAudioVisibleTo(otherCampus, campusUser), false);
  assert.equal(isAudioVisibleTo(otherOrg, campusUser), false);
});

test('global-access users see everything', () => {
  assert.equal(isAudioVisibleTo(otherOrg, globalUser), true);
});

// --- management ---

test('a campus user manages only own-org uploads, never a global default', () => {
  assert.equal(canManageAudioFile(sameCampus, campusUser), true);
  assert.equal(canManageAudioFile(orgWide, campusUser), true);
  assert.equal(canManageAudioFile(globalDefault, campusUser), false);
  assert.equal(canManageAudioFile(otherOrg, campusUser), false);
});

test('global-access users may manage any row including defaults', () => {
  assert.equal(canManageAudioFile(globalDefault, globalUser), true);
  assert.equal(canManageAudioFile(otherOrg, globalUser), true);
});
