import { describe, expect, it } from 'vitest';
import {
  normalizeConnectorId,
  normalizeConnectorScopes,
  normalizeLeaseEpoch,
  normalizeLogicalAgentIdentity,
  normalizeLogicalBindingId,
  type ConnectorExecutionContext,
  type LogicalAgentIdentity,
} from './connector-lease.dto.js';

describe('logical agent connector lease contract', (): void => {
  it('normalizes a runtime-neutral logical identity and binding vocabulary', (): void => {
    const identity = normalizeLogicalAgentIdentity({
      tenantId: ' tenant-01 ',
      logicalAgentId: ' MOS.Primary ',
    });

    expect(identity).toEqual({ tenantId: 'tenant-01', logicalAgentId: 'mos.primary' });
    expect(normalizeLogicalBindingId(' Discord:Operations ')).toBe('discord:operations');
    expect(normalizeConnectorId(' PI.Worker-01 ')).toBe('pi.worker-01');
    expect(Object.isFrozen(identity)).toBe(true);
    expect(Object.keys(identity).sort()).toEqual(['logicalAgentId', 'tenantId']);
  });

  it('canonicalizes scopes and decimal fencing epochs', (): void => {
    expect(normalizeConnectorScopes([' Runtime.Send ', 'tool.execute', 'runtime.send'])).toEqual([
      'runtime.send',
      'tool.execute',
    ]);
    expect(normalizeLeaseEpoch('00042')).toBe('42');
  });

  it.each([
    ['', 'mos'],
    ['tenant', ''],
    ['tenant', 'claude session/123'],
  ])('rejects ambiguous identity values tenant=%j agent=%j', (tenantId, logicalAgentId): void => {
    expect(() => normalizeLogicalAgentIdentity({ tenantId, logicalAgentId })).toThrow();
  });

  it('defines an adapter context without harness-native identity fields', (): void => {
    const identity: LogicalAgentIdentity = { tenantId: 'tenant-01', logicalAgentId: 'mos' };
    const context: ConnectorExecutionContext = {
      identity,
      bindingId: 'operator-chat',
      connectorId: 'connector-a',
      leaseId: '00000000-0000-4000-8000-000000000001',
      leaseEpoch: '7',
      scopes: ['runtime.send'],
      correlationId: 'correlation-1',
      grantExpiresAt: '2026-07-14T18:00:00.000Z',
    };

    expect(context).not.toHaveProperty('sessionId');
    expect(context).not.toHaveProperty('tmuxSession');
    expect(context).not.toHaveProperty('providerSessionId');
  });
});
