import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  CrossCompanyReferenceError,
  CustomerNotActiveError,
  CustomerNotFoundError,
  InvalidOrderLineError,
  ItemNotActiveError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseChannel,
  baseCompany,
  baseCustomer,
  baseCustomerRole,
  baseItem,
  baseOrderLineInput,
  baseSalesOrder,
  baseSalesOrderLine,
  inactiveCustomer,
  inactiveItem,
  otherCompanyItem,
} from "../testing/fixtures";
import { mockBPQueries, mockItemQueries } from "../testing/moduleMocks";
import { run } from "./createSalesOrder";

describe("createSalesOrder", () => {
  it("creates a draft sales order with valid customer and lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [baseSalesOrder], [baseSalesOrderLine]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: baseCompany.id,
            customerId: baseCustomer.id,
            channelId: baseChannel.id,
          },
          lines: [baseOrderLineInput],
        },
        commandCtx,
        mockBPQueries(baseCustomer, baseCustomerRole),
        mockItemQueries([baseItem]),
      ),
    );

    const value = expectOk(result);
    expect(value.salesOrder.status).toBe("DRAFT");
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ companyId: baseCompany.id, customerId: baseCustomer.id }),
    );
  });

  it("throws when customer does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, customerId: baseCustomer.id },
          lines: [baseOrderLineInput],
        },
        commandCtx,
        mockBPQueries(null, baseCustomerRole),
        mockItemQueries([]),
      ),
    );

    expectErr(result, CustomerNotFoundError);
  });

  it("throws when customer is inactive or lacks CUSTOMER role", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, customerId: inactiveCustomer.id },
          lines: [baseOrderLineInput],
        },
        commandCtx,
        mockBPQueries(inactiveCustomer, baseCustomerRole),
        mockItemQueries([]),
      ),
    );

    expectErr(result, CustomerNotActiveError);
  });

  it("throws when an order line references an inactive item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, customerId: baseCustomer.id },
          lines: [baseOrderLineInput],
        },
        commandCtx,
        mockBPQueries(baseCustomer, baseCustomerRole),
        mockItemQueries([{ ...inactiveItem, id: baseOrderLineInput.itemId }]),
      ),
    );

    expectErr(result, ItemNotActiveError);
  });

  it("throws when line quantity is zero or unit price is negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, customerId: baseCustomer.id },
          lines: [{ ...baseOrderLineInput, quantity: 0, unitPrice: -1 }],
        },
        commandCtx,
        mockBPQueries(baseCustomer, baseCustomerRole),
        mockItemQueries([]),
      ),
    );

    expectErr(result, InvalidOrderLineError);
  });

  it("throws when references cross company boundaries", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, customerId: baseCustomer.id },
          lines: [baseOrderLineInput],
        },
        commandCtx,
        mockBPQueries(baseCustomer, baseCustomerRole),
        mockItemQueries([{ ...otherCompanyItem, id: baseOrderLineInput.itemId }]),
      ),
    );

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