import { describe, it, expect, beforeEach } from 'vitest';
import { Repository } from './repository.js';

describe('Repository a2a oidc', () => {
  let repo: Repository;
  beforeEach(() => { repo = new Repository(':memory:'); });

  it('upserts and finds an oidc model payload', () => {
    repo.oidcUpsert('AccessToken', 'tok1', { foo: 'bar' }, { expiresAt: null, grantId: 'g1' });
    const row = repo.oidcFind('AccessToken', 'tok1');
    expect(row?.payload).toEqual({ foo: 'bar' });
    expect(row?.consumedAt).toBeNull();
  });

  it('consume sets consumedAt and revokeByGrantId deletes all rows of that grant', () => {
    repo.oidcUpsert('AuthorizationCode', 'c1', { x: 1 }, { grantId: 'g1' });
    repo.oidcUpsert('AccessToken', 't1', { x: 2 }, { grantId: 'g1' });
    repo.oidcConsume('AuthorizationCode', 'c1', 1234);
    expect(repo.oidcFind('AuthorizationCode', 'c1')?.consumedAt).toBe(1234);
    repo.oidcRevokeByGrantId('g1');
    expect(repo.oidcFind('AuthorizationCode', 'c1')).toBeUndefined();
    expect(repo.oidcFind('AccessToken', 't1')).toBeUndefined();
  });

  it('finds Session by uid', () => {
    repo.oidcUpsert('Session', 's1', { accountId: 'u1' }, { uid: 'uid-1' });
    expect(repo.oidcFindByUid('uid-1')?.payload).toEqual({ accountId: 'u1' });
  });

  it('creates and reads an a2a client', () => {
    repo.createA2aClient({
      clientId: 'cli1', name: 'Tester', redirectUris: ['https://x/cb'],
      secretHash: 'abc', tokenEndpointAuthMethod: 'client_secret_basic',
      agentCardUrl: null, issuer: null, keyFingerprint: null, status: 'active', createdBy: 'admin1',
    });
    const got = repo.getA2aClient('cli1');
    expect(got?.redirectUris).toEqual(['https://x/cb']);
    expect(got?.status).toBe('active');
  });
});
