import assert from 'node:assert/strict';
import test from 'node:test';

import { assertFileExists, readText } from './helpers.ts';

test('first-run bootstrap setup public surfaces exist', () => {
  for (const route of ['status', 'preview', 'commit', 'complete']) {
    assertFileExists(`src/app/api/setup/bootstrap/${route}/route.ts`);
  }

  assertFileExists('src/app/administration/setup/page.tsx');
  assertFileExists('src/features/setup/components/setup-wizard.tsx');
  assertFileExists('src/features/setup/server/setup-bootstrap.service.ts');
  assertFileExists('src/features/setup/server/setup-import-source.service.ts');
});

test('bootstrap setup guards public access after initialization', () => {
  const service = readText('src/features/setup/server/setup-bootstrap.service.ts');
  const templatesRoute = readText('src/app/api/setup/templates/route.ts');
  const proxy = readText('src/proxy.ts');

  assert.match(service, /completedSetupRun/);
  assert.match(service, /superAdminUser/);
  assert.match(service, /adminMembership/);
  assert.match(service, /BOOTSTRAP_SETUP_TOKEN/);
  assert.match(service, /Bootstrap setup is no longer available/);
  assert.match(templatesRoute, /getBootstrapSetupStatus/);
  assert.match(templatesRoute, /requireSystemRole\('super_admin'\)/);
  assert.match(proxy, /\/administration\/setup/);
  assert.match(proxy, /\/api\/setup\/bootstrap\//);
  assert.match(proxy, /\/api\/setup\/templates/);
});

test('bootstrap setup supports configured-directory preview and commit', () => {
  const service = readText('src/features/setup/server/setup-bootstrap.service.ts');
  const commitRoute = readText('src/app/api/setup/bootstrap/commit/route.ts');
  const previewRoute = readText('src/app/api/setup/bootstrap/preview/route.ts');

  for (const fileName of [
    'users.csv',
    'organizations.csv',
    'memberships.csv',
    'crm-role-assignments.csv',
    'master-options.csv',
    'branches.csv',
    'product-types.csv',
    'document-sequences.csv',
    'approval-workflows.csv',
    'approval-steps.csv',
    'approval-matrix.csv'
  ]) {
    assert.match(service, new RegExp(fileName.replace('.', '\\.')));
  }

  assert.match(previewRoute, /application\/json/);
  assert.match(previewRoute, /configured-directory/);
  assert.match(previewRoute, /readConfiguredSetupImportSource/);
  assert.match(previewRoute, /saveConfiguredPreviewSteps/);

  assert.match(commitRoute, /application\/json/);
  assert.match(commitRoute, /configured-directory/);
  assert.match(commitRoute, /previewHash/);
  assert.match(commitRoute, /commitSetupCsvImport/);
  assert.match(commitRoute, /saveConfiguredCommitSteps/);
  assert.match(commitRoute, /skipStaleInvalidation: true/);
  assert.match(previewRoute, /skipStaleInvalidation: true/);
});
