import { strict as assert } from 'node:assert';
import { randomBytes } from 'node:crypto';
import { describe, it } from 'node:test';
import type { Config } from '../src/lib/config';
import {
  inviteMetadata,
  isInferenceEndpoint,
  memberAccessSchema,
  platformSettingsResponse,
  platformSettingsSchema,
} from '../src/routes/admin-settings';
import { decryptSecret, encryptSecret, SecretConfigurationError } from '../src/lib/secrets';

describe('admin settings decisions', () => {
  it('keeps inference separate from the Prime compute API host', () => {
    assert.equal(isInferenceEndpoint('https://api.pinference.ai/api/v1'), true);
    assert.equal(isInferenceEndpoint('https://api.primeintellect.ai'), false);
    assert.equal(
      platformSettingsSchema.safeParse({
        piggyInferenceBase: 'https://api.primeintellect.ai/v1',
      }).success,
      false,
    );
  });

  it('encrypts credentials with authenticated random envelopes and requires an external key', () => {
    const key = randomBytes(32).toString('base64');
    const first = encryptSecret('prime-secret', key);
    const second = encryptSecret('prime-secret', key);
    assert.notEqual(first, second);
    assert.equal(decryptSecret(first, key), 'prime-secret');
    assert.throws(
      () => encryptSecret('prime-secret', undefined),
      (error: unknown) => error instanceof SecretConfigurationError,
    );
  });

  it('never returns a stored key, ciphertext, or invite hash in metadata', () => {
    const now = new Date('2026-08-12T12:00:00.000Z');
    const settings = platformSettingsResponse(
      {
        id: 'default',
        piggyModel: 'nvidia/nemotron-3-nano-30b-a3b',
        piggyInferenceBase: 'https://api.pinference.ai/api/v1',
        piggyEnabled: true,
        primeApiKeyEncrypted: 'v1.iv.tag.ciphertext',
        primeApiKeyUpdatedAt: now,
        // Present so the row is a complete PlatformSettings. The assertion
        // below is that nothing secret escapes into the metadata, and the
        // Learn share code is exactly the sort of thing that must not.
        learnAccessCode: 'carlthefog',
        learnAccessCodeUpdatedAt: null,
        primeSyncEnabled: true,
        primeSyncIntervalMinutes: 30,
        updatedByUserId: null,
        updatedAt: now,
      },
      {
        PRIME_API_KEY: 'environment-secret',
        PRIME_API_BASE: 'https://api.primeintellect.ai',
      } as Config,
    );
    assert.equal(JSON.stringify(settings).includes('ciphertext'), false);
    assert.equal(JSON.stringify(settings).includes('environment-secret'), false);

    const invite = inviteMetadata({
      id: '00000000-0000-0000-0000-000000000001',
      codeHash: 'never-return-this',
      email: null,
      team: null,
      role: 'member',
      createdByUserId: null,
      expiresAt: null,
      usesRemaining: 1,
      scopeNote: null,
      redeemedByUserId: null,
      redeemedAt: null,
      revokedAt: null,
      createdAt: now,
    });
    assert.equal('codeHash' in invite, false);
  });

  it('rejects duplicate team assignments rather than depending on a database conflict', () => {
    assert.equal(
      memberAccessSchema.safeParse({
        isPlatformAdmin: false,
        memberships: [
          { team: 'supply', role: 'member' },
          { team: 'supply', role: 'admin' },
        ],
      }).success,
      false,
    );
  });
});
