import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MemoryDatastoreProvider } from '@bytelyst/datastore';
import { _resetDatastoreProvider, setProvider } from '../../lib/datastore.js';
import * as repo from './repository.js';

describe('scim repository', () => {
  beforeEach(() => {
    setProvider(new MemoryDatastoreProvider());
  });

  afterEach(() => {
    _resetDatastoreProvider();
  });

  it('stores connectors, sync state, and provisioning events', async () => {
    await repo.createConnector({
      id: 'scim_1',
      orgId: 'org_1',
      productId: 'lysnrai',
      name: 'Okta Provisioning',
      authMode: 'bearer',
      status: 'active',
      createdBy: 'admin_1',
      createdAt: '2026-03-15T00:00:00.000Z',
      updatedAt: '2026-03-15T00:00:00.000Z',
    });

    await repo.upsertUserSync({
      id: 'scim_1:user:ext_1',
      orgId: 'org_1',
      connectorId: 'scim_1',
      productId: 'lysnrai',
      externalUserId: 'ext_1',
      email: 'member@acme.com',
      status: 'provisioned',
      lastSyncedAt: '2026-03-15T00:05:00.000Z',
    });

    await repo.createEvent({
      id: 'scimevt_1',
      orgId: 'org_1',
      connectorId: 'scim_1',
      productId: 'lysnrai',
      entityType: 'user',
      entityId: 'ext_1',
      action: 'provision',
      status: 'success',
      createdAt: '2026-03-15T00:06:00.000Z',
    });

    const connectors = await repo.listConnectors('org_1');
    const users = await repo.listUserSync('scim_1');
    const events = await repo.listEvents('scim_1');

    expect(connectors).toHaveLength(1);
    expect(users[0].email).toBe('member@acme.com');
    expect(events[0].action).toBe('provision');
  });
});
