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

describe("getProductionOrder", () => {
  it("returns a production order with material requirements, work orders, and cost summary when found", async () => {
    const mock = createKyselyMock<Namespace["main-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,
    };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [baseBomSnapshot],
      [baseRoutingSnapshot],
      [baseCostBaseline],
      [materialReq],
      [workOrder1, workOrder2],
      [costSummary],
    );

    const result = await run(mock.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");

    expect(mock.selects).toHaveLength(7);
    expect(mock.selects[0].parameters).toContain(baseReleasedProductionOrder.id);
    expect(mock.selects[0].sql).toMatch(/"id"/);
    expect(mock.selects[1].parameters).toContain(baseReleasedProductionOrder.id);
    expect(mock.selects[1].sql).toMatch(/"productionOrderId"/);
    expect(mock.selects[2].sql).toMatch(/"productionOrderId"/);
    expect(mock.selects[3].sql).toMatch(/"productionOrderId"/);
    expect(mock.selects[4].sql).toMatch(/"productionOrderId"/);
    expect(mock.selects[5].sql).toMatch(/"productionOrderId"/);
    expect(mock.selects[5].sql).toMatch(/order by .*"routingOperationSequenceNumber" asc/i);
    expect(mock.selects[6].sql).toMatch(/"productionOrderId"/);
  });

  it("returns a production order with no cost summary when none exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseReleasedProductionOrder], [], [], [], [], [], []);

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

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