import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CrossCompanyReferenceError,
  CustomerNotActiveError,
  CustomerNotFoundError,
  InvalidOrderLineError,
  ItemNotActiveError,
} from "../lib/errors.generated";
import {
  baseChannel,
  baseCompany,
  baseCustomer,
  baseCustomerRole,
  baseOrderLineInput,
  baseSalesOrder,
  baseSalesOrderLine,
  inactiveCustomer,
  inactiveItem,
  otherCompanyItem,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createSalesOrder";

describe("createSalesOrder", () => {
  it("creates a draft sales order with valid customer and lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCustomer)
      .mockReturnValueOnce([baseCustomerRole])
      .mockReturnValueOnce({
        ...otherCompanyItem,
        id: baseOrderLineInput.itemId,
        companyId: baseCompany.id,
        status: "ACTIVE",
      })
      .mockReturnValueOnce(baseChannel);
    spies.insert.mockReturnValueOnce(baseSalesOrder).mockReturnValueOnce(baseSalesOrderLine);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        customerId: baseCustomer.id,
        channelId: baseChannel.id,
        lines: [baseOrderLineInput],
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.salesOrder.status).toBe("DRAFT");
    expect(spies.values).toHaveBeenNthCalledWith(
      1,
      expect.objectContaining({ companyId: baseCompany.id, customerId: baseCustomer.id }),
    );
  });

  it("throws when customer does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { companyId: baseCompany.id, customerId: baseCustomer.id, lines: [baseOrderLineInput] },
      commandCtx,
    );

    expectErr(result, CustomerNotFoundError);
  });

  it("throws when customer is inactive or lacks CUSTOMER role", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveCustomer);

    const result = await run(
      db,
      { companyId: baseCompany.id, customerId: inactiveCustomer.id, lines: [baseOrderLineInput] },
      commandCtx,
    );

    expectErr(result, CustomerNotActiveError);
  });

  it("throws when an order line references an inactive item", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCustomer)
      .mockReturnValueOnce([baseCustomerRole])
      .mockReturnValueOnce(inactiveItem);

    const result = await run(
      db,
      { companyId: baseCompany.id, customerId: baseCustomer.id, lines: [baseOrderLineInput] },
      commandCtx,
    );

    expectErr(result, ItemNotActiveError);
  });

  it("throws when line quantity is zero or unit price is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCustomer).mockReturnValueOnce([baseCustomerRole]);

    const result = await run(
      db,
      {
        companyId: baseCompany.id,
        customerId: baseCustomer.id,
        lines: [{ ...baseOrderLineInput, quantity: 0, unitPrice: -1 }],
      },
      commandCtx,
    );

    expectErr(result, InvalidOrderLineError);
  });

  it("throws when references cross company boundaries", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseCustomer)
      .mockReturnValueOnce([baseCustomerRole])
      .mockReturnValueOnce(otherCompanyItem);

    const result = await run(
      db,
      { companyId: baseCompany.id, customerId: baseCustomer.id, lines: [baseOrderLineInput] },
      commandCtx,
    );

    expectErr(result, CrossCompanyReferenceError);
  });
});
