import assert from 'node:assert/strict';
import test from 'node:test';
import {
  getLegacyManagementMetadata,
  getManagementMetadata,
  mergeManagementMetadata,
  sanitizeTemplateSchemaJson,
} from './metadata';

test('sanitizeTemplateSchemaJson removes embedded legacy management metadata', () => {
  const schemaJson = {
    basePdf: { width: 210, height: 297, padding: [0, 0, 0, 0] },
    schemas: [],
    __templateManagement: {
      lifecycleStatus: 'published',
      runtimeVersion: 'p5',
    },
  };

  assert.deepEqual(sanitizeTemplateSchemaJson(schemaJson), {
    basePdf: { width: 210, height: 297, padding: [0, 0, 0, 0] },
    schemas: [],
  });
});

test('getManagementMetadata falls back to legacy schema metadata when metadata_json is absent', () => {
  const metadata = getManagementMetadata({
    schemaJson: {
      schemas: [],
      __templateManagement: {
        lifecycleStatus: 'validated',
        runtimeVersion: 'legacy-runtime',
      },
    },
  });

  assert.equal(metadata.lifecycleStatus, 'validated');
  assert.equal(metadata.runtimeVersion, 'legacy-runtime');
});

test('mergeManagementMetadata prefers dedicated metadata_json but preserves compatibility fallback', () => {
  const metadata = mergeManagementMetadata({
    currentMetadataJson: {
      lifecycleStatus: 'draft',
      runtimeVersion: 'p5.1',
    },
    currentSchemaJson: {
      __templateManagement: {
        lifecycleStatus: 'published',
        runtimeVersion: 'legacy-runtime',
      },
    },
    patch: {
      lifecycleStatus: 'active',
      publishedBy: 'user-1',
    },
  });

  assert.equal(metadata.lifecycleStatus, 'active');
  assert.equal(metadata.runtimeVersion, 'p5.1');
  assert.equal(metadata.publishedBy, 'user-1');
});

test('getLegacyManagementMetadata returns empty object for clean PDFMe schema', () => {
  assert.deepEqual(
    getLegacyManagementMetadata({
      basePdf: { width: 210, height: 297, padding: [0, 0, 0, 0] },
      schemas: [],
    }),
    {},
  );
});
