import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidCreditNoteLineError, InvoiceNotIssuedError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseCreditNote,
  baseCreditNoteLineInput,
  baseSalesInvoice,
  baseSalesInvoiceLine,
  issuedSalesInvoice,
} from "../testing/fixtures";
import { run } from "./createSalesCreditNote";

describe("createSalesCreditNote", () => {
  it("creates a draft credit note against an issued invoice", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const invoiceLine = { ...baseSalesInvoiceLine, salesInvoiceId: issuedSalesInvoice.id };
    mock.enqueueResults([issuedSalesInvoice], [invoiceLine], [baseCreditNote]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { salesInvoiceId: issuedSalesInvoice.id },
          lines: [baseCreditNoteLineInput],
        },
        commandCtx,
      ),
    );

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

  it("throws when invoice is not issued", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesInvoice]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { header: { salesInvoiceId: baseSalesInvoice.id }, lines: [baseCreditNoteLineInput] },
        commandCtx,
      ),
    );

    expectErr(result, InvoiceNotIssuedError);
  });

  it("throws when no correction line is provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([issuedSalesInvoice]);

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

    expectErr(result, InvalidCreditNoteLineError);
  });
});
