import { test } from 'node:test';
import assert from 'node:assert/strict';
import { tenantWhere } from '@/db/api/shared/repository';
import type { CurrentUser } from '@/db/api/types';

/**
 * Unit tests for pure repository helpers.
 *
 * Tests for `findOwnedByPk`, `deleteRecordsByIds`, and `autocompleteByField`
 * require Sequelize model mocks which would need type assertions. Those
 * functions are covered by integration tests instead.
 */

const ORG_A = '11111111-1111-1111-1111-111111111111';
const ORG_B = '22222222-2222-2222-2222-222222222222';

const userOrgA: CurrentUser = { id: 'u1', organizationId: ORG_A };
const globalUser: CurrentUser = {
  id: 'g1',
  organizationId: ORG_A,
  app_role: { globalAccess: true },
};

test('tenantWhere scopes a non-global user to their organization', () => {
  assert.deepEqual(tenantWhere(userOrgA), { organizationId: ORG_A });
});

test('tenantWhere returns no clause for a global-access user', () => {
  assert.deepEqual(tenantWhere(globalUser), {});
});

test('tenantWhere returns no clause when there is no user/org', () => {
  assert.deepEqual(tenantWhere(undefined), {});
  assert.deepEqual(tenantWhere({ id: null }), {});
});

test('tenantWhere prefers the loaded organizations.id over the scalar', () => {
  const user: CurrentUser = {
    id: 'u2',
    organizations: { id: ORG_B },
    organizationId: ORG_A,
  };
  assert.deepEqual(tenantWhere(user), { organizationId: ORG_B });
});
