import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CrossCompanyReferenceError, InvalidInvoiceLineError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseInvoiceLineInput,
  baseSalesInvoice,
  baseSalesInvoiceLine,
  baseSalesOrderLine,
  confirmedSalesOrder,
} from "../testing/fixtures";
import { run } from "./createSalesInvoice";

describe("createSalesInvoice", () => {
  it("creates a draft invoice for a valid order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: confirmedSalesOrder.id };
    mock.enqueueResults(
      [confirmedSalesOrder],
      [orderLine],
      [baseSalesInvoice],
      [orderLine],
      [baseSalesInvoiceLine],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [baseInvoiceLineInput],
        },
        commandCtx,
      ),
    );

    const value = expectOk(result);
    expect(value.salesInvoice.status).toBe("DRAFT");
  });

  it("throws when no invoice lines are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([confirmedSalesOrder]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [],
        },
        commandCtx,
      ),
    );

    expectErr(result, InvalidInvoiceLineError);
  });

  it("throws when invoice line references an unknown sales-order line", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([confirmedSalesOrder], []);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [baseInvoiceLineInput],
        },
        commandCtx,
      ),
    );

    expectErr(result, InvalidInvoiceLineError);
  });

  it("throws when order belongs to another company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...confirmedSalesOrder, companyId: "company-2" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [baseInvoiceLineInput],
        },
        commandCtx,
      ),
    );

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