import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseSalesInvoice, issuedSalesInvoice, baseSalesInvoiceLine } from "../testing/fixtures";
import { run } from "./getSalesInvoice";

describe("getSalesInvoice", () => {
  it("returns invoice when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesInvoice], [baseSalesInvoiceLine]);

    const result = await run(mock.db, { id: baseSalesInvoice.id });
    const { salesInvoice } = expectOk<{ salesInvoice: unknown }>(result as never);

    expect(salesInvoice).not.toBeNull();
    expect(salesInvoice).toMatchObject({ id: baseSalesInvoice.id });
  });

  it("returns issued invoice with due schedule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([issuedSalesInvoice], [baseSalesInvoiceLine]);

    const result = await run(mock.db, { id: issuedSalesInvoice.id });
    const { salesInvoice } = expectOk<{
      salesInvoice: { status: string; dueSchedule: unknown[] };
    }>(result as never);

    expect(salesInvoice.status).toBe("ISSUED");
    expect(salesInvoice.dueSchedule).toHaveLength(1);
  });

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

    const result = await run(mock.db, { id: "non-existent-id" });
    const { salesInvoice } = expectOk<{ salesInvoice: null }>(result as never);

    expect(salesInvoice).toBeNull();
  });
});
