import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

import {
  isIntegrationMtlsEnabled,
  normalizeCertificateFingerprint,
  verifyClientCertificateFingerprint,
} from '@hexahost/integration-auth';

describe('integration mTLS utilities', () => {
  it('normalizes fingerprint colons', () => {
    const normalized = normalizeCertificateFingerprint('AB:CD:EF');
    assert.equal(normalized, 'abcdef');
  });

  it('verifies matching fingerprints', () => {
    assert.equal(
      verifyClientCertificateFingerprint('ab:cd', 'abcd'),
      true,
    );
  });
});

describe('whmcs mtls and product mapping contract', () => {
  it('documents mTLS guard and API routes', () => {
    const guard = readFileSync(
      join(process.cwd(), 'src', 'integrations/whmcs/whmcs-integration.guard.ts'),
      'utf8',
    );
    assert.ok(guard.includes('isIntegrationMtlsEnabled'));
    assert.ok(guard.includes('assertIntegrationMtls'));

    const controller = readFileSync(
      join(process.cwd(), 'src', 'integrations/whmcs/whmcs-integration.controller.ts'),
      'utf8',
    );
    assert.ok(controller.includes("'mtls/status'"));
    assert.ok(controller.includes("'mtls/fingerprint'"));
    assert.ok(controller.includes("'catalog/validate-plan'"));
  });

  it('documents addon product mapping and shared resolver', () => {
    const addon = readFileSync(
      join(process.cwd(), '..', '..', 'integrations/whmcs/modules/addons/hexagamecloud/hexagamecloud.php'),
      'utf8',
    );
    assert.ok(addon.includes('hexagamecloud_page_mappings'));
    assert.ok(addon.includes('ProductMappingStorage'));

    const resolver = readFileSync(
      join(process.cwd(), '..', '..', 'integrations/whmcs/lib/ProductMapping.php'),
      'utf8',
    );
    assert.ok(resolver.includes('resolvePlanSlug'));
  });

  it('defaults mTLS disabled outside production flag', () => {
    const previous = process.env['INTEGRATION_MTLS_ENABLED'];
    delete process.env['INTEGRATION_MTLS_ENABLED'];
    assert.equal(isIntegrationMtlsEnabled(), false);
    if (previous !== undefined) {
      process.env['INTEGRATION_MTLS_ENABLED'] = previous;
    }
  });
});
