import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '../../src/core/Arbiter.js';
import { PartialGraphContext } from '../../src/core/PartialGraphContext.js';

function setupArbiter() {
  const arbiter = new Arbiter();
  arbiter.addNode('request:1', 'request');
  arbiter.addNode('time:now', 'timestamp');
  return arbiter;
}

test('ADR-042 reducers are first-class in PartialGraphContext conflict resolution', () => {
  const arbiter = setupArbiter();
  const ctx = new PartialGraphContext(arbiter, {
    options: {
      reducers: {
        request_has_timestamp: 'latest'
      }
    },
    relations: [
      {
        src: 'request:1',
        relation: 'request_has_timestamp',
        dst: 'time:now',
        value: 100,
        updated_last_at: 100,
        layer_name: 'request_observed'
      },
      {
        src: 'request:1',
        relation: 'request_has_timestamp',
        dst: 'time:now',
        value: 200,
        updated_last_at: 200,
        layer_name: 'request_observed'
      }
    ]
  });

  const srcId = arbiter.nodeIdByKey.get('request:1');
  const dstId = arbiter.nodeIdByKey.get('time:now');
  const direct = ctx.getDirectRelation(srcId, 'request_has_timestamp', dstId);
  assert.ok(direct);
  assert.equal(direct.value, 200);
  const audit = ctx.getReducerAudit();
  assert.ok(audit.some((entry) => entry.type === 'relation_conflict_resolved'));
});

test('ADR-042 strict conflict mode rejects unresolved same-triple conflicts', () => {
  const arbiter = setupArbiter();
  assert.throws(() => {
    new PartialGraphContext(arbiter, {
      options: {
        strictConflicts: true
      },
      relations: [
        {
          src: 'request:1',
          relation: 'request_has_id',
          dst: 'time:now',
          value: 1,
          layer_name: 'request_observed'
        },
        {
          src: 'request:1',
          relation: 'request_has_id',
          dst: 'time:now',
          value: 2,
          layer_name: 'request_observed'
        }
      ]
    });
  }, /partial_graph_conflict_without_reducer/);
});

test('ADR-042 invalid reducer configuration is reported in reducer audit', () => {
  const arbiter = setupArbiter();
  const ctx = new PartialGraphContext(arbiter, {
    options: {
      reducers: {
        delegated_authority: 'strongest'
      }
    },
    relations: []
  });
  const audit = ctx.getReducerAudit();
  assert.ok(audit.some((entry) => entry.type === 'invalid_reducer_config'));
});
