import { describe, it, expect } from 'vitest';
import {
  isAdmin,
  assertAdmin,
  resolveTenantId,
  canAccessTenant,
  type AuthUser,
} from '@/lib/auth/authz';

const reformista: AuthUser = {
  id: 'u1', email: 'r@x.com', nombre: 'R', role: 'reformista', tenantId: 't1', status: 'activo',
};
const admin: AuthUser = {
  id: 'u2', email: 'a@x.com', nombre: 'A', role: 'admin', tenantId: null, status: 'activo',
};

describe('authz', () => {
  it('isAdmin distingue roles', () => {
    expect(isAdmin(admin)).toBe(true);
    expect(isAdmin(reformista)).toBe(false);
  });

  it('assertAdmin lanza si no es admin o es null', () => {
    expect(() => assertAdmin(admin)).not.toThrow();
    expect(() => assertAdmin(reformista)).toThrow();
    expect(() => assertAdmin(null)).toThrow();
  });

  it('resolveTenantId devuelve el tenant del reformista y lanza para admin/null', () => {
    expect(resolveTenantId(reformista)).toBe('t1');
    expect(() => resolveTenantId(admin)).toThrow();
    expect(() => resolveTenantId(null)).toThrow();
  });

  it('canAccessTenant: reformista solo el suyo, admin cualquiera', () => {
    expect(canAccessTenant(reformista, 't1')).toBe(true);
    expect(canAccessTenant(reformista, 't2')).toBe(false);
    expect(canAccessTenant(admin, 't2')).toBe(true);
  });
});
