import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { IdentifierRequiredError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseListing, retiredListing, baseChannel } from "../testing/fixtures";
import { run } from "./getListingByExternalIdentifier";

describe("getListingByExternalIdentifier", () => {
  it("returns listing by external identifier", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseListing]);

    const result = await run(mock.db, {
      channelId: baseChannel.id,
      externalIdentifier: "AMZ-001",
    });
    const { listing } = expectOk<{ listing: typeof baseListing | null }>(result as never);

    expect(listing).not.toBeNull();
    expect(listing!.id).toBe(baseListing.id);
  });

  it("returns retired listing when historical reference is needed", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([retiredListing]);

    const result = await run(mock.db, {
      channelId: baseChannel.id,
      externalIdentifier: "AMZ-001",
    });
    const { listing } = expectOk<{ listing: typeof retiredListing | null }>(result as never);

    expect(listing).not.toBeNull();
    expect(listing!.status).toBe("RETIRED");
  });

  it("returns null when no listing matches the external identifier", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, {
      channelId: baseChannel.id,
      externalIdentifier: "NONEXISTENT",
    });
    const { listing } = expectOk<{ listing: null }>(result as never);

    expect(listing).toBeNull();
  });

  it("throws when channel id or external identifier is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await run(mock.db, {
      channelId: "",
      externalIdentifier: "test",
    });

    expectErr(result as never, IdentifierRequiredError);
  });
});
