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 { baseSalesOrder, baseSalesOrderLine } from "../testing/fixtures";
import { run } from "./getSalesOrder";

describe("getSalesOrder", () => {
  it("returns sales order when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesOrder], [baseSalesOrderLine]);

    const result = await run(mock.db, { id: baseSalesOrder.id });
    const { salesOrder } = expectOk<{ salesOrder: unknown }>(result as never);

    expect(salesOrder).not.toBeNull();
    expect(salesOrder).toMatchObject({ id: baseSalesOrder.id });
  });

  it("returns line-level shipped and invoiced progress", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesOrder], [baseSalesOrderLine]);

    const result = await run(mock.db, { id: baseSalesOrder.id });
    const { salesOrder } = expectOk<{
      salesOrder: {
        fulfillmentTotals: {
          totalOrdered: number;
          totalShipped: number;
          totalInvoiced: number;
          openToShip: number;
          openToInvoice: number;
        };
      };
    }>(result as never);

    expect(salesOrder.fulfillmentTotals).toEqual({
      totalOrdered: 10,
      totalShipped: 0,
      totalInvoiced: 0,
      openToShip: 10,
      openToInvoice: 10,
    });
  });

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

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

    expect(salesOrder).toBeNull();
  });
});
