import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseSalesInvoice, issuedSalesInvoice, baseSalesInvoiceLine } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getSalesInvoice";

describe("getSalesInvoice", () => {
  it("returns invoice when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSalesInvoice);
    spies.select.mockReturnValueOnce([baseSalesInvoiceLine]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(issuedSalesInvoice);
    spies.select.mockReturnValueOnce([baseSalesInvoiceLine]);

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

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

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