import test from 'node:test';
import assert from 'node:assert/strict';
import { parseMatrixUri } from '@open-matrix/federation/uri';

test('parse compact URI with realm + mount + atom', () => {
  const u = parseMatrixUri('acme.com/env/prod/root.ui.app.editor.accepts.setText');
  assert.ok(u);
  assert.equal(u!.realm, 'acme.com');
  assert.deepEqual(u!.mountSegments, ['env', 'prod']);
  assert.equal(u!.componentPath, 'root.ui.app.editor');
  assert.equal(u!.plane, 'accepts');
  assert.equal(u!.messageName, 'setText');
  assert.equal(u!.toPath, 'env/prod/root.ui.app.editor.accepts.setText');
});

test('parse segmented MXURI/1 with /-/', () => {
  const u = parseMatrixUri('acme.com/env/prod/-/root/ui/app/editor/accepts/setText');
  assert.ok(u);
  assert.equal(u!.realm, 'acme.com');
  assert.equal(u!.toPath, 'env/prod/root.ui.app.editor.accepts.setText');
});

test('tab normalization (~tab)', () => {
  const u = parseMatrixUri('flowpad-demo/~tab/abc123/-/root/ui/app/accepts/ping');
  assert.ok(u);
  assert.equal(u!.realm, 'flowpad-demo.tab.abc123');
  assert.equal(u!.toPath, 'root.ui.app.accepts.ping');
});

test('query params parsed (defaults)', () => {
  const u = parseMatrixUri('matrix-3/project/daemon.project.accepts.scan?depth=2&hidden=false');
  assert.ok(u);
  assert.equal(u!.query.depth, '2');
  assert.equal(u!.query.hidden, 'false');
});

test('parse compact URI local-only (no realm)', () => {
  const u = parseMatrixUri('root.ui.app.accepts.ping');
  assert.ok(u);
  assert.equal(u!.realm, undefined);
  assert.equal(u!.toPath, 'root.ui.app.accepts.ping');
  assert.equal(u!.componentPath, 'root.ui.app');
  assert.equal(u!.plane, 'accepts');
  assert.equal(u!.messageName, 'ping');
});

test('tab normalization works in compact form (no /-/)', () => {
  const u = parseMatrixUri('flowpad-demo/~tab/xyz/root.ui.app.accepts.ping');
  assert.ok(u);
  assert.equal(u!.realm, 'flowpad-demo.tab.xyz');
  assert.equal(u!.toPath, 'root.ui.app.accepts.ping');
});

test('invalid URI (missing accepts/emits plane) returns null', () => {
  const u = parseMatrixUri('acme.com/env/prod/root.ui.app.editor/setText');
  assert.equal(u, null);
});

test('non-matrix scheme returns null', () => {
  const u = parseMatrixUri('http://example.com/path');
  assert.equal(u, null);
});
