import { describe, expect, it } from 'vitest';
import {
  hasPermission,
  hasAnyPermission,
  hasAllPermissions,
} from '@/business/auth/permissions';
import type { CurrentUser } from '@/shared/types/auth';

function user(overrides: Partial<CurrentUser> = {}): CurrentUser {
  return {
    id: 'u1',
    email: 'staff@example.com',
    permissions: [],
    ...overrides,
  };
}

describe('permission selectors', () => {
  it('grants a permission the user holds and denies one they do not', () => {
    const u = user({ permissions: ['READ_CAMPUSES', 'READ_DASHBOARD'] });
    expect(hasPermission(u, 'READ_CAMPUSES')).toBe(true);
    expect(hasPermission(u, 'DELETE_CAMPUSES')).toBe(false);
  });

  it('treats a global-access role as having every permission', () => {
    const admin = user({
      permissions: [],
      app_role: { name: 'super_admin', globalAccess: true },
    });
    expect(hasPermission(admin, 'DELETE_ORGANIZATIONS')).toBe(true);
    expect(hasAllPermissions(admin, ['CREATE_USERS', 'DELETE_USERS'])).toBe(true);
  });

  it('denies everything for a null user', () => {
    expect(hasPermission(null, 'READ_CAMPUSES')).toBe(false);
    expect(hasAnyPermission(null, ['READ_CAMPUSES'])).toBe(false);
  });

  it('hasAnyPermission needs at least one; hasAllPermissions needs all', () => {
    const u = user({ permissions: ['READ_FRAME'] });
    expect(hasAnyPermission(u, ['READ_FRAME', 'READ_DIRECTOR_DASHBOARD'])).toBe(true);
    expect(hasAllPermissions(u, ['READ_FRAME', 'READ_DIRECTOR_DASHBOARD'])).toBe(false);
    expect(hasAllPermissions(u, ['READ_FRAME'])).toBe(true);
  });

  it('does not treat a non-global role with empty permissions as all-access', () => {
    const teacher = user({
      permissions: [],
      app_role: { name: 'teacher', globalAccess: false },
    });
    expect(hasPermission(teacher, 'READ_FRAME')).toBe(false);
  });
});
