'use strict';

// IMP-CODE-02: the migration arrays were extracted from db/database.js into
// factory modules. These guard the invariants db/database.js relies on:
//  - both modules load and build their arrays (run/check bodies aren't invoked
//    at construction, so empty deps are fine);
//  - the versioned list has no duplicate versions;
//  - every legacy-reconcile version exists in the versioned list (reconcile only
//    marks known migrations as applied — a reconcile version with no versioned
//    counterpart is the drift the in-app assertion warns about).
const test = require('node:test');
const assert = require('node:assert/strict');

const buildVersioned = require('../db/migrations/versionedMigrations');
const buildReconcile = require('../db/migrations/legacyReconcileMigrations');

test('both migration modules build their arrays with no deps needed at construction', () => {
  const versioned = buildVersioned({});
  const reconcile = buildReconcile({});
  assert.ok(Array.isArray(versioned) && versioned.length > 0, 'versioned array non-empty');
  assert.ok(Array.isArray(reconcile) && reconcile.length > 0, 'reconcile array non-empty');
  for (const m of versioned) assert.equal(typeof m.run, 'function', `${m.version} has a run()`);
  for (const m of reconcile) assert.equal(typeof m.check, 'function', `${m.version} has a check()`);
});

test('versioned migration versions are unique', () => {
  const versions = buildVersioned({}).map(m => m.version);
  assert.equal(new Set(versions).size, versions.length, 'no duplicate versions');
});

test('every legacy-reconcile version exists in the versioned list (no drift)', () => {
  const versionedSet = new Set(buildVersioned({}).map(m => m.version));
  const orphans = buildReconcile({}).map(m => m.version).filter(v => !versionedSet.has(v));
  assert.deepEqual(orphans, [], `reconcile versions with no versioned counterpart: ${orphans.join(', ')}`);
});
