import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { ProductionOrderNotFoundError } from "../lib/errors.generated";
import {
  baseReleasedProductionOrder,
  baseBomSnapshot,
  baseRoutingSnapshot,
  baseCostBaseline,
  baseMaterialRequirement,
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseCollectingCostSummary,
} from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { run } from "./getProductionOrder";

describe("getProductionOrder", () => {
  it("returns a production order with material requirements, work orders, and cost summary when found", async () => {
    const { db, spies } = createMockDb<DB>();
    const materialReq = {
      ...baseMaterialRequirement,
      productionOrderId: baseReleasedProductionOrder.id,
    };
    const workOrder1 = {
      ...basePendingWorkOrder,
      productionOrderId: baseReleasedProductionOrder.id,
    };
    const workOrder2 = {
      ...baseInProgressWorkOrder,
      productionOrderId: baseReleasedProductionOrder.id,
    };
    const costSummary = {
      ...baseCollectingCostSummary,
      productionOrderId: baseReleasedProductionOrder.id,
    };

    // 1st select: productionOrder
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // 2nd-4th select: snapshots and baseline
    spies.select.mockReturnValueOnce(baseBomSnapshot);
    spies.select.mockReturnValueOnce(baseRoutingSnapshot);
    spies.select.mockReturnValueOnce(baseCostBaseline);
    // 5th select: materialRequirements
    spies.select.mockReturnValueOnce([materialReq]);
    // 6th select: workOrders
    spies.select.mockReturnValueOnce([workOrder1, workOrder2]);
    // 7th select: costSummary
    spies.select.mockReturnValueOnce(costSummary);

    const result = await run(db, { id: baseReleasedProductionOrder.id });
    const {
      productionOrder,
      bomSnapshot,
      routingSnapshot,
      costBaseline,
      materialRequirements,
      workOrders,
      quantityRollup,
      costSummary: cs,
    } = expectOk<{
      productionOrder: { id: string; status: string; selectedBomVersionId: string | null };
      bomSnapshot: { productionOrderId: string } | null;
      routingSnapshot: { routingId: string } | null;
      costBaseline: { currencyCode: string } | null;
      materialRequirements: { id: string; itemId: string }[];
      workOrders: { id: string; status: string }[];
      quantityRollup: { completedQuantity: number; openWorkOrderCount: number };
      costSummary: { id: string; status: string } | null;
    }>(result as never);

    expect(productionOrder.id).toBe(baseReleasedProductionOrder.id);
    expect(productionOrder.status).toBe("RELEASED");
    expect(productionOrder.selectedBomVersionId).toBe("bom-2");
    expect(bomSnapshot?.productionOrderId).toBe(baseReleasedProductionOrder.id);
    expect(routingSnapshot?.routingId).toBe(baseRoutingSnapshot.routingId);
    expect(costBaseline?.currencyCode).toBe("USD");
    expect(materialRequirements).toHaveLength(1);
    expect(materialRequirements[0].itemId).toBe("item-2");
    expect(workOrders).toHaveLength(2);
    expect(quantityRollup.completedQuantity).toBe(50);
    expect(quantityRollup.openWorkOrderCount).toBe(2);
    expect(cs).not.toBeNull();
    expect(cs!.status).toBe("COLLECTING");
  });

  it("returns a production order with no cost summary when none exists", async () => {
    const { db, spies } = createMockDb<DB>();

    // 1st select: productionOrder
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // 2nd-4th select: snapshots and baseline
    spies.select.mockReturnValueOnce(undefined);
    spies.select.mockReturnValueOnce(undefined);
    spies.select.mockReturnValueOnce(undefined);
    // 5th select: materialRequirements
    spies.select.mockReturnValueOnce([]);
    // 6th select: workOrders
    spies.select.mockReturnValueOnce([]);
    // 7th select: costSummary returns undefined
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: baseReleasedProductionOrder.id });
    const {
      productionOrder,
      bomSnapshot,
      routingSnapshot,
      costBaseline,
      materialRequirements,
      workOrders,
      costSummary,
    } = expectOk<{
      productionOrder: { id: string };
      bomSnapshot: null;
      routingSnapshot: null;
      costBaseline: null;
      materialRequirements: unknown[];
      workOrders: unknown[];
      costSummary: null;
    }>(result as never);

    expect(productionOrder.id).toBe(baseReleasedProductionOrder.id);
    expect(bomSnapshot).toBeNull();
    expect(routingSnapshot).toBeNull();
    expect(costBaseline).toBeNull();
    expect(materialRequirements).toHaveLength(0);
    expect(workOrders).toHaveLength(0);
    expect(costSummary).toBeNull();
  });

  it("returns error when the production order does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    // 1st select: productionOrder returns undefined
    spies.select.mockReturnValueOnce(undefined);

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