import { describe, it, expect } from 'vitest';
import { parseRoleBinding } from '../../src/commands/rbac-bindings.js';

describe('parseRoleBinding', () => {
  it('parses an unscoped resource binding', () => {
    expect(parseRoleBinding('role:view,resource:servers')).toEqual({
      role: 'view',
      resource: 'servers',
    });
  });

  it('parses a name-scoped resource binding', () => {
    expect(parseRoleBinding('role:view,resource:servers,name:my-ha')).toEqual({
      role: 'view',
      resource: 'servers',
      name: 'my-ha',
    });
  });

  it('parses an operation binding via the action shorthand', () => {
    expect(parseRoleBinding('action:logs')).toEqual({
      role: 'run',
      action: 'logs',
    });
  });

  it('trims whitespace around keys and values', () => {
    expect(parseRoleBinding('role: edit , resource: * ')).toEqual({
      role: 'edit',
      resource: '*',
    });
  });

  it('rejects a pair with no colon', () => {
    expect(() => parseRoleBinding('role=view')).toThrow(/key:value pairs/);
  });

  it('rejects an unknown key', () => {
    expect(() => parseRoleBinding('role:view,resource:servers,scope:project')).toThrow(/Invalid roleBindings key 'scope'/);
  });

  it('rejects an empty value', () => {
    expect(() => parseRoleBinding('role:view,resource:')).toThrow(/empty key or value/);
  });

  it('rejects action combined with resource/name', () => {
    expect(() => parseRoleBinding('action:logs,resource:servers')).toThrow(/cannot be combined/);
  });

  it('requires both role and resource when action is absent', () => {
    expect(() => parseRoleBinding('role:view')).toThrow(/need either 'action/);
    expect(() => parseRoleBinding('resource:servers')).toThrow(/need either 'action/);
  });
});
