import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { CompanyScopeRequiredError } from "../lib/errors.generated";
import {
  baseSalesOrder,
  submittedSalesOrder,
  baseSalesOrderLine,
  baseCompany,
  baseCustomer,
} from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listSalesOrders";

describe("listSalesOrders", () => {
  it("lists sales orders by company scope", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseSalesOrder]);
    spies.select.mockReturnValueOnce(baseSalesOrder);
    spies.select.mockReturnValueOnce([baseSalesOrderLine]);

    const result = await run(db, { companyId: baseCompany.id });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("filters sales orders by status and customer when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([submittedSalesOrder]);
    spies.select.mockReturnValueOnce(submittedSalesOrder);
    spies.select.mockReturnValueOnce([baseSalesOrderLine]);

    const result = await run(db, {
      companyId: baseCompany.id,
      status: "SUBMITTED",
      customerId: baseCustomer.id,
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("returns summary open-balance metrics", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseSalesOrder]);
    spies.select.mockReturnValueOnce(baseSalesOrder);
    spies.select.mockReturnValueOnce([baseSalesOrderLine]);

    const result = await run(db, { companyId: baseCompany.id });
    const { items } = expectOk<{
      items: {
        fulfillmentTotals: {
          totalOrdered: number;
          totalShipped: number;
          totalInvoiced: number;
          openToShip: number;
          openToInvoice: number;
        };
      }[];
      hasNextPage: boolean;
    }>(result as never);

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

  it("throws when company scope is missing", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { companyId: "" });
    expectErr(result as never, CompanyScopeRequiredError);
  });
});
