import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseSupplyPlan } from "../testing/fixtures";
import { run } from "./getInventorySupplyPlan";

describe("getInventorySupplyPlan", () => {
  it("returns supply plan by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSupplyPlan);

    const result = await run(db, { id: "supply-plan-1" });
    expect(result.ok).toBe(true);
    const { supplyPlan } = result.value;

    expect(supplyPlan?.id).toBe("supply-plan-1");
  });

  it("returns supply plan by source line", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSupplyPlan);

    const result = await run(db, {
      sourceType: "PURCHASE_ORDER",
      sourceLineId: "po-line-1",
    });
    expect(result.ok).toBe(true);
    const { supplyPlan } = result.value;

    expect(supplyPlan?.id).toBe("supply-plan-1");
    expect(spies.where).toHaveBeenCalledWith("sourceType", "=", "PURCHASE_ORDER");
    expect(spies.where).toHaveBeenCalledWith("sourceLineId", "=", "po-line-1");
  });

  it("returns null when not found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "missing" });
    expect(result.ok).toBe(true);
    const { supplyPlan } = result.value;

    expect(supplyPlan).toBeNull();
  });

  it("computes open quantity", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({
      ...baseSupplyPlan,
      expectedQuantity: "100",
      receivedQuantity: "25",
    });

    const result = await run(db, { id: "supply-plan-1" });
    expect(result.ok).toBe(true);
    const { supplyPlan } = result.value;

    expect(supplyPlan?.openQuantity).toBe("75");
  });

  it("returns zero open quantity when received quantity exceeds expected quantity", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({
      ...baseSupplyPlan,
      expectedQuantity: "80",
      receivedQuantity: "100",
    });

    const result = await run(db, { id: "supply-plan-1" });
    expect(result.ok).toBe(true);
    const { supplyPlan } = result.value;

    expect(supplyPlan?.openQuantity).toBe("0");
  });

  it("returns closed supply plan with zero open quantity", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({
      ...baseSupplyPlan,
      expectedQuantity: "100",
      receivedQuantity: "25",
      status: "CLOSED",
    });

    const result = await run(db, { id: "supply-plan-1" });
    expect(result.ok).toBe(true);
    const { supplyPlan } = result.value;

    expect(supplyPlan?.status).toBe("CLOSED");
    expect(supplyPlan?.openQuantity).toBe("0");
  });
});
