import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidCreditNoteLineError, InvoiceNotIssuedError } from "../lib/errors.generated";
import {
  baseCreditNote,
  baseCreditNoteLineInput,
  baseSalesInvoice,
  baseSalesInvoiceLine,
  issuedSalesInvoice,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createSalesCreditNote";

describe("createSalesCreditNote", () => {
  it("creates a draft credit note against an issued invoice", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const invoiceLine = { ...baseSalesInvoiceLine, salesInvoiceId: issuedSalesInvoice.id };
    spies.select.mockReturnValueOnce(issuedSalesInvoice).mockReturnValueOnce(invoiceLine);
    spies.insert.mockReturnValueOnce(baseCreditNote).mockReturnValueOnce(undefined);

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

    const result = await run(
      db,
      { salesInvoiceId: baseSalesInvoice.id, lines: [baseCreditNoteLineInput] },
      commandCtx,
    );

    expectErr(result, InvoiceNotIssuedError);
  });

  it("throws when no correction line is provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(issuedSalesInvoice);

    const result = await run(db, { salesInvoiceId: issuedSalesInvoice.id, lines: [] }, commandCtx);

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