import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseSalesOrder, baseSalesOrderLine } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getSalesOrder";

describe("getSalesOrder", () => {
  it("returns sales order when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSalesOrder);
    spies.select.mockReturnValueOnce([baseSalesOrderLine]);

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

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

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

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