import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseAvailableSerial } from "../testing/fixtures";
import { run } from "./getSerialNumber";

describe("getSerialNumber", () => {
  it("returns serial when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial]);

    const result = await run(mock.db, { id: "serial-1" });
    const { serialNumber } = expectOk<{ serialNumber: unknown }>(result as never);

    expect(serialNumber).not.toBeNull();
    expect(serialNumber).toMatchObject({ id: "serial-1" });
  });

  it("returns serial when found by serialNumber and itemId", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial]);

    const result = await run(mock.db, {
      serialNumber: "SN-001",
      itemId: "item-1",
    });
    const { serialNumber } = expectOk<{ serialNumber: unknown }>(result as never);

    expect(serialNumber).not.toBeNull();
    expect(serialNumber).toMatchObject({
      id: "serial-1",
      serialNumber: "SN-001",
    });
  });

  it("returns null when not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "non-existent" });
    const { serialNumber } = expectOk<{ serialNumber: null }>(result as never);

    expect(serialNumber).toBeNull();
  });

  it("includes current status and location", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial]);

    const result = await run(mock.db, { id: "serial-1" });
    const { serialNumber } = expectOk<{
      serialNumber: { status: string; storageLocationId: string };
    }>(result as never);

    expect(serialNumber.status).toBe("AVAILABLE");
    expect(serialNumber.storageLocationId).toBe("location-1");
  });
});
