import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CrossCompanyReferenceError, InvalidInvoiceLineError } from "../lib/errors.generated";
import {
  baseInvoiceLineInput,
  baseSalesInvoice,
  baseSalesInvoiceLine,
  baseSalesOrderLine,
  confirmedSalesOrder,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createSalesInvoice";

describe("createSalesInvoice", () => {
  it("creates a draft invoice for a valid order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: confirmedSalesOrder.id };
    spies.select
      .mockReturnValueOnce(confirmedSalesOrder)
      .mockReturnValueOnce(orderLine)
      .mockReturnValueOnce(orderLine);
    spies.insert.mockReturnValueOnce(baseSalesInvoice).mockReturnValueOnce(baseSalesInvoiceLine);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(confirmedSalesOrder);

    const result = await run(
      db,
      { companyId: confirmedSalesOrder.companyId, salesOrderId: confirmedSalesOrder.id, lines: [] },
      commandCtx,
    );

    expectErr(result, InvalidInvoiceLineError);
  });

  it("throws when invoice line references an unknown sales-order line", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(confirmedSalesOrder).mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        companyId: confirmedSalesOrder.companyId,
        salesOrderId: confirmedSalesOrder.id,
        lines: [baseInvoiceLineInput],
      },
      commandCtx,
    );

    expectErr(result, InvalidInvoiceLineError);
  });

  it("throws when order belongs to another company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...confirmedSalesOrder, companyId: "company-2" });

    const result = await run(
      db,
      {
        companyId: confirmedSalesOrder.companyId,
        salesOrderId: confirmedSalesOrder.id,
        lines: [baseInvoiceLineInput],
      },
      commandCtx,
    );

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