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 { baseCreditNote, issuedCreditNote, baseCreditNoteLine } from "../testing/fixtures";
import { run } from "./getSalesCreditNote";

describe("getSalesCreditNote", () => {
  it("returns credit note when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseCreditNote], [baseCreditNoteLine]);

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

    expect(salesCreditNote).not.toBeNull();
    expect(salesCreditNote).toMatchObject({ id: baseCreditNote.id });
  });

  it("returns issued credit note with correction lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([issuedCreditNote], [baseCreditNoteLine]);

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

    expect(salesCreditNote.status).toBe("ISSUED");
    expect(salesCreditNote.lines).toHaveLength(1);
  });

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

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

    expect(salesCreditNote).toBeNull();
  });
});
