import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseEventCategoryBinding, baseOptionalEventBinding } from "../testing/fixtures";
import { run } from "./getEventCategoryBinding";

describe("getEventCategoryBinding", () => {
  it("returns the binding when found by eventType", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEventCategoryBinding }]);

    const result = await run(mock.db, { eventType: "PO_ISSUED" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.binding).not.toBeNull();
      expect(result.value.binding?.eventType).toBe("PO_ISSUED");
    }
  });

  it("returns null when the eventType is not present in the catalog", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { eventType: "UNKNOWN_EVENT" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.binding).toBeNull();
    }
  });

  it("returns transactional = true for transactional events (host-seeded examples: INVOICE_APPROVED, SUPPLIER_SUSPENDED)", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEventCategoryBinding }]);

    const result = await run(mock.db, { eventType: "PO_ISSUED" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.binding?.transactional).toBe(true);
    }
  });

  it("returns transactional = false for optional events (host-seeded examples: ANNOUNCEMENT_PUBLISHED, RFQ_PUBLISHED)", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseOptionalEventBinding }]);

    const result = await run(mock.db, { eventType: "ANNOUNCEMENT_PUBLISHED" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.binding?.transactional).toBe(false);
    }
  });

  it("returns the host-seeded defaultChannels[] array on the row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEventCategoryBinding }]);

    const result = await run(mock.db, { eventType: "PO_ISSUED" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.binding?.defaultChannels).toEqual(["IN_APP", "EMAIL"]);
    }
  });
});
