import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import {
  baseDraftBom,
  baseActiveBom,
  baseInactiveBom,
  baseBomLine,
  baseBomLine2,
} from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { BomNotFoundError } from "../lib/errors.generated";
import { run } from "./getBillOfMaterial";

describe("getBillOfMaterial", () => {
  it("returns a BOM with component lines when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseActiveBom);
    spies.select.mockReturnValueOnce([baseBomLine, baseBomLine2]);

    const result = await run(db, { id: baseActiveBom.id });
    const { billOfMaterial, lines } = expectOk<{
      billOfMaterial: unknown;
      lines: unknown[];
    }>(result as never);

    expect(billOfMaterial).toMatchObject({ id: baseActiveBom.id });
    expect(lines).toHaveLength(2);
  });

  it("returns draft BOM versions when requested", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftBom);
    spies.select.mockReturnValueOnce([baseBomLine]);

    const result = await run(db, { id: baseDraftBom.id });
    const { billOfMaterial } = expectOk<{
      billOfMaterial: { status: string };
    }>(result as never);

    expect(billOfMaterial.status).toBe("DRAFT");
  });

  it("returns inactive BOM versions when requested", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInactiveBom);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { id: baseInactiveBom.id });
    const { billOfMaterial } = expectOk<{
      billOfMaterial: { status: string };
    }>(result as never);

    expect(billOfMaterial.status).toBe("INACTIVE");
  });

  it("returns error when the BOM does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent-id" });
    expectErr(result as never, BomNotFoundError);
  });
});
