import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { BomNotFoundError } from "../lib/errors.generated";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import {
  baseDraftBom,
  baseActiveBom,
  baseInactiveBom,
  baseBomLine,
  baseBomLine2,
} from "../testing/fixtures";
import { run } from "./getBillOfMaterial";

describe("getBillOfMaterial", () => {
  it("returns a BOM with component lines when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveBom], [baseBomLine, baseBomLine2]);

    const result = await run(mock.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);
    expect(mock.selects).toHaveLength(2);
    expect(mock.selects[0].parameters).toContain(baseActiveBom.id);
    expect(mock.selects[0].sql).toMatch(/"id"/);
    expect(mock.selects[1].parameters).toContain(baseActiveBom.id);
    expect(mock.selects[1].sql).toMatch(/"billOfMaterialId"/);
  });

  it("returns draft BOM versions when requested", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftBom], [baseBomLine]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactiveBom], []);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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