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

const ledgerEntry = {
  id: "ledger-1",
  inventoryExecutionId: "execution-1",
  executionType: "GOODS_RECEIPT" as const,
  sourceDocumentId: "source-1",
  dcIndicator: "DR" as const,
  itemId: "item-1",
  storageLocationId: "location-1",
  quantity: 1,
  executedAt: new Date("2024-01-02T00:00:00.000Z"),
  lotId: null,
  serialNumberId: "serial-1",
  createdAt: new Date("2024-01-01T00:00:00.000Z"),
};

describe("getSerialNumberHistory", () => {
  it("returns full history ordered by executedAt ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial], [ledgerEntry]);

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

    expect(entries).toHaveLength(1);
    expect(mock.selects[1].sql).toMatch(/order by .*"executedAt" asc/i);
  });

  it("includes executionType and storageLocationId per entry", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial], [ledgerEntry]);

    const result = await run(mock.db, { serialNumberId: "serial-1" });
    const { entries } = expectOk<{
      entries: { executionType: string; executedAt: Date }[];
    }>(result as never);

    expect(entries[0].executionType).toBe("GOODS_RECEIPT");
    expect(entries[0].executedAt).toEqual(new Date("2024-01-02T00:00:00.000Z"));
  });

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

    const result = await run(mock.db, { serialNumberId: "serial-1" });
    const { entries } = expectOk<{
      entries: {
        storageLocationId: string;
      }[];
    }>(result as never);

    expect(entries[0].storageLocationId).toBe("location-1");
  });

  it("includes execution source document for traceability", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial], [ledgerEntry]);

    const result = await run(mock.db, { serialNumberId: "serial-1" });
    const { entries } = expectOk<{
      entries: {
        executionType: string;
        sourceDocumentId: string;
      }[];
    }>(result as never);

    expect(entries[0].executionType).toBe("GOODS_RECEIPT");
    expect(entries[0].sourceDocumentId).toBe("source-1");
  });

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

    const result = await run(mock.db, { serialNumberId: "non-existent" });

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

  it("returns empty history for newly created serial", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvailableSerial], []);

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

    expect(entries).toEqual([]);
  });
});
