import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { DeliveryMetadataRequiredError, InvalidInvoiceStatusError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { issuedSalesInvoice, sentSalesInvoice } from "../testing/fixtures";
import { run } from "./sendSalesInvoice";

describe("sendSalesInvoice", () => {
  it("marks an issued invoice as sent when delivery metadata is present", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([issuedSalesInvoice], [sentSalesInvoice]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([sentSalesInvoice]);

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

    expectErr(result, InvalidInvoiceStatusError);
  });

  it("throws when delivery metadata is incomplete", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([issuedSalesInvoice]);

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

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