import assert from 'node:assert/strict';
import { existsSync } from 'node:fs';
import path from 'node:path';
import test from 'node:test';

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

interface TemplateMetadata {
  templates: Array<{ file: string; supported: boolean }>;
}

const requiredFiles = [
  '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'
];

test('setup import source service resolves env-based configured folder', () => {
  const service = readText('src/features/setup/server/setup-import-source.service.ts');

  assert.match(service, /SETUP_IMPORT_DIR/);
  assert.match(service, /\.\/setup\/ALLA-ONVALLA/);
  assert.match(service, /process\.cwd\(\)/);
  assert.match(service, /path\.resolve/);
  assert.match(service, /missingRequiredFiles/);
  assert.match(service, /ignoredFiles/);
  assert.match(service, /checksum/);
  assert.match(service, /getCsvTemplateRegistry/);
});

test('sample ALLA setup folder contains required bootstrap CSV files', () => {
  const folder = path.join(repoRoot, 'setup', 'ALLA-ONVALLA');
  assert.equal(existsSync(folder), true, 'setup/ALLA-ONVALLA should exist');

  for (const fileName of requiredFiles) {
    assertFileExists(`setup/ALLA-ONVALLA/${fileName}`);
  }
});

test('configured setup import source only reads registered supported templates', () => {
  const metadata = readJson<TemplateMetadata>('setup/templates/templates.json');
  const supportedFiles = new Set(
    metadata.templates.filter((template) => template.supported).map((template) => template.file)
  );

  for (const fileName of requiredFiles) {
    assert.equal(supportedFiles.has(fileName), true, `${fileName} should be a supported setup template`);
  }

  const service = readText('src/features/setup/server/setup-import-source.service.ts');
  assert.match(service, /template\.supported/);
  assert.match(service, /File is not a registered supported setup CSV template/);
});

test('environment documents setup import directory', () => {
  const env = readText('.env');
  assert.match(env, /SETUP_IMPORT_DIR=\.\/setup\/ALLA-ONVALLA/);
});
