import assert from "node:assert/strict";
import { resolveManagedReaderScope, resolveManagedReaderSourceConnection } from "../src/reader-source-scope.mjs";

const policy = {
  tenantId: "tenant-01",
  connectionId: "consumer-connection",
  providerId: "provider-01",
  allowedDataProductIds: ["fleet.positions.current.v1"],
};

assert.equal(
  await resolveManagedReaderSourceConnection(db(["producer-connection"]), policy),
  "producer-connection",
);
assert.equal(
  await resolveManagedReaderSourceConnection(db(["producer-connection", "consumer-connection"]), policy),
  "consumer-connection",
);
await assert.rejects(
  resolveManagedReaderSourceConnection(db([]), policy),
  (error) => error?.status === 409 && error?.code === "managed_reader_source_scope_not_found",
);

assert.deepEqual(
  await resolveManagedReaderScope(scopeDb([
    { tenantId: "tenant-01", connectionId: "producer-connection", providerId: "provider-01" },
  ]), policy.allowedDataProductIds),
  { tenantId: "tenant-01", connectionId: "producer-connection", providerId: "provider-01" },
);
await assert.rejects(
  resolveManagedReaderScope(scopeDb([]), policy.allowedDataProductIds),
  (error) => error?.status === 409 && error?.code === "managed_consumer_reader_source_scope_not_found",
);
await assert.rejects(
  resolveManagedReaderScope(scopeDb([
    { tenantId: "tenant-01", connectionId: "producer-a", providerId: "provider-01" },
    { tenantId: "tenant-01", connectionId: "producer-b", providerId: "provider-01" },
  ]), policy.allowedDataProductIds),
  (error) => error?.status === 409 && error?.code === "managed_consumer_reader_source_scope_ambiguous",
);
await assert.rejects(
  resolveManagedReaderSourceConnection(db(["producer-a", "producer-b"]), policy),
  (error) => error?.status === 409 && error?.code === "managed_reader_source_scope_ambiguous",
);
await assert.rejects(
  resolveManagedReaderSourceConnection(db(["producer-connection"]), { ...policy, allowedDataProductIds: [] }),
  (error) => error?.status === 400 && error?.code === "managed_reader_source_scope_request_invalid",
);

function db(connectionIds) {
  return {
    async query(sql, values) {
      assert.match(sql, /external_data_plane_writer_bindings/);
      assert.deepEqual(values, [policy.tenantId, policy.providerId, policy.allowedDataProductIds]);
      return { rows: connectionIds.map((connectionId) => ({ connectionId })) };
    },
  };
}

function scopeDb(rows) {
  return {
    async query(sql, values) {
      assert.match(sql, /external_data_plane_writer_bindings/);
      assert.deepEqual(values, [policy.allowedDataProductIds]);
      return { rows };
    },
  };
}

console.log("external-data-plane reader source scope: ok");
