import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { DeliveryMetadataRequiredError, InvalidInvoiceStatusError } from "../lib/errors.generated";
import { issuedSalesInvoice, sentSalesInvoice } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./sendSalesInvoice";

describe("sendSalesInvoice", () => {
  it("marks an issued invoice as sent when delivery metadata is present", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(issuedSalesInvoice);
    spies.update.mockReturnValueOnce(sentSalesInvoice);

    const result = await run(
      db,
      { salesInvoiceId: issuedSalesInvoice.id, deliveryMetadata: { method: "EMAIL" } },
      commandCtx,
    );

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

  it("throws when invoice is not issued", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(sentSalesInvoice);

    const result = await run(
      db,
      { salesInvoiceId: sentSalesInvoice.id, deliveryMetadata: { method: "EMAIL" } },
      commandCtx,
    );

    expectErr(result, InvalidInvoiceStatusError);
  });

  it("throws when delivery metadata is incomplete", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(issuedSalesInvoice);

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

    expectErr(result, DeliveryMetadataRequiredError);
  });
});
