import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import {
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseActiveWorkCenter,
} from "../testing/fixtures";
import { WorkCenterReferenceRequiredError, WorkCenterNotFoundError } from "../lib/errors.generated";
import { run } from "./listWorkOrdersByWorkCenter";

describe("listWorkOrdersByWorkCenter", () => {
  it("lists pending and in-progress work orders for one work center across multiple production orders", async () => {
    const { db, spies } = createMockDb<DB>();
    const workOrderFromAnotherPO = {
      ...basePendingWorkOrder,
      id: "work-order-10",
      productionOrderId: "production-order-3",
    };
    // 1st select: WorkCenter lookup
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // 2nd select: WorkOrder list
    spies.select.mockReturnValueOnce([
      basePendingWorkOrder,
      baseInProgressWorkOrder,
      workOrderFromAnotherPO,
    ]);

    const result = await run(db, {
      workCenterId: "work-center-2",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(3);
  });

  it("filters work orders by status when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    // 1st select: WorkCenter lookup
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // 2nd select: WorkOrder list filtered by status
    spies.select.mockReturnValueOnce([baseInProgressWorkOrder]);

    const result = await run(db, {
      workCenterId: "work-center-2",
      status: "IN_PROGRESS",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseInProgressWorkOrder);
  });

  it("orders the result for bottleneck review by execution priority and planned timing", async () => {
    const { db, spies } = createMockDb<DB>();
    const workOrderSeq20 = {
      ...basePendingWorkOrder,
      id: "work-order-20",
      routingOperationSequenceNumber: 20,
    };
    // 1st select: WorkCenter lookup
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // 2nd select: WorkOrder list ordered by routingOperationSequenceNumber asc
    spies.select.mockReturnValueOnce([basePendingWorkOrder, workOrderSeq20]);

    const result = await run(db, {
      workCenterId: "work-center-2",
    });
    const { items } = expectOk<{
      items: { routingOperationSequenceNumber: number }[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items[0].routingOperationSequenceNumber).toBe(10);
    expect(items[1].routingOperationSequenceNumber).toBe(20);
  });

  it("returns summary fields with production-order reference operation sequence and progress totals", async () => {
    const { db, spies } = createMockDb<DB>();
    // 1st select: WorkCenter lookup
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // 2nd select: WorkOrder list
    spies.select.mockReturnValueOnce([baseInProgressWorkOrder]);

    const result = await run(db, {
      workCenterId: "work-center-2",
    });
    const { items } = expectOk<{
      items: {
        productionOrderId: string;
        routingOperationSequenceNumber: number;
        completedQuantity: number;
        plannedQuantity: number;
      }[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items[0].productionOrderId).toBe("production-order-2");
    expect(items[0].routingOperationSequenceNumber).toBe(10);
    expect(items[0].completedQuantity).toBe(50);
    expect(items[0].plannedQuantity).toBe(100);
  });

  it("returns an empty list when the work center has no assigned work orders", async () => {
    const { db, spies } = createMockDb<DB>();
    // 1st select: WorkCenter lookup
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // 2nd select: empty WorkOrder list
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, {
      workCenterId: "work-center-2",
    });
    const { items, hasNextPage } = expectOk<{
      items: unknown[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items).toHaveLength(0);
    expect(hasNextPage).toBe(false);
  });

  it("returns error when the work-center reference is missing", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, {
      workCenterId: "",
    });
    expectErr(result as never, WorkCenterReferenceRequiredError);
  });

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

    const result = await run(db, {
      workCenterId: "nonexistent-wc",
    });
    expectErr(result as never, WorkCenterNotFoundError);
  });
});
