import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseCreditNote, issuedCreditNote, baseCreditNoteLine } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getSalesCreditNote";

describe("getSalesCreditNote", () => {
  it("returns credit note when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseCreditNote);
    spies.select.mockReturnValueOnce([baseCreditNoteLine]);

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

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

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

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