import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { IdentifierRequiredError } from "../lib/errors.generated";
import { baseListing, retiredListing, baseChannel } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./getListingByExternalIdentifier";

describe("getListingByExternalIdentifier", () => {
  it("returns listing by external identifier", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseListing);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(retiredListing);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(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 { db } = createMockDb<DB>();

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

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