import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CompanyScopeRequiredError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseSalesOrder,
  submittedSalesOrder,
  baseSalesOrderLine,
  baseCompany,
  baseCustomer,
} from "../testing/fixtures";
import { run } from "./listSalesOrders";

describe("listSalesOrders", () => {
  it("lists sales orders by company scope", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesOrder], [baseSalesOrder], [baseSalesOrderLine]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain(baseCompany.id);
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"orderDate" desc/i);
  });

  it("filters sales orders by status and customer when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([submittedSalesOrder], [submittedSalesOrder], [baseSalesOrderLine]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("SUBMITTED");
    expect(mock.selects[0].parameters).toContain(baseCustomer.id);
    expect(mock.selects[0].sql).toMatch(/"status"/);
    expect(mock.selects[0].sql).toMatch(/"customerId"/);
  });

  it("returns summary open-balance metrics", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesOrder], [baseSalesOrder], [baseSalesOrderLine]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();

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