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

describe('MatrixDSLHost login-required bootstrap', () => {
  it('does not auto-redirect matrix-web away from its own login/signup shell', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /hostedAppName !== 'web'/);
    assert.match(source, /this\._redirectToPlatformLogin\(\)/);
  });

  it('reserves device handoff for the edge Device shell', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /_shouldRedirectToDeviceLogin\(hostedAppName/);
    assert.match(source, /normalizedAppName === 'edge'/);
    assert.match(source, /this\._redirectToDeviceLogin\(\)/);
  });

  it('keeps the NATS backbone available for authenticated Matrix Web namespace setup', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /const natsWsUrl = natsWsAttr \?\? \(!discoveredNats \? backboneUrl : null\);/);
    assert.doesNotMatch(source, /renderNamespaceSetupLocally\s*\?\s*null\s*:/);
  });

  it('does not query platform registry metadata for the Matrix Web shell itself', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /const appName = this\._deriveHostedAppName\(\);[\s\S]*if \(!appName\) return;[\s\S]*if \(appName === 'web'\) return;/);
  });

  it('does not query platform registry metadata for standalone apps before a user Space is selected', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /const platformServiceRoot = \(this\.dataset\.platformServiceRoot \?\? ''\)\.trim\(\);/);
    assert.match(source, /if \(platformServiceRoot && selectedAuthorityRoot === platformServiceRoot && !isPlatformAdmin\) \{\s*return;\s*\}/);
  });

  it('does not claim platform service registry entries for browser apps before a user Space is selected', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /this\._shouldSkipBrowserRuntimeRegistryClaim\(controlPlaneRoot\)/);
    assert.match(source, /result: 'skipped-no-registry-authority'/);
    assert.match(source, /return !candidateAuthorityRoots\.some\(\(root\) => root\.length > 0 && root !== platformRoot\);/);
  });

  it('does not claim browser runtime registry entries when this Host is not the authority coordinator', () => {
    const source = readFileSync(resolve(import.meta.dirname, '../MatrixDSLHost.ts'), 'utf8');

    assert.match(source, /bootstrapNodeRoleActive\(bootstrap\.nodeRoles, 'authorityCoordinator'\)/);
    assert.match(source, /this\.dataset\.authorityCoordinatorActive === 'false'/);
  });
});
