import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { WorkCenterReferenceRequiredError, WorkCenterNotFoundError } from "../lib/errors.generated";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import {
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseActiveWorkCenter,
} from "../testing/fixtures";
import { run } from "./listWorkOrdersByWorkCenter";

describe("listWorkOrdersByWorkCenter", () => {
  it("lists pending and in-progress work orders for one work center across multiple production orders", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const workOrderFromAnotherPO = {
      ...basePendingWorkOrder,
      id: "work-order-10",
      productionOrderId: "production-order-3",
    };
    mock.enqueueResults(
      [baseActiveWorkCenter],
      [basePendingWorkOrder, baseInProgressWorkOrder, workOrderFromAnotherPO],
    );

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

    expect(items).toHaveLength(3);

    expect(mock.selects).toHaveLength(2);
    expect(mock.selects[0].sql).toMatch(/"id"/);
    expect(mock.selects[0].parameters).toContain("work-center-2");
    expect(mock.selects[1].sql).toMatch(/"workCenterId"/);
    expect(mock.selects[1].parameters).toContain("work-center-2");
    expect(mock.selects[1].sql).toMatch(/order by .*"routingOperationSequenceNumber" asc/i);
  });

  it("filters work orders by status when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveWorkCenter], [baseInProgressWorkOrder]);

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

    expect(mock.selects[1].sql).toMatch(/"status"/);
    expect(mock.selects[1].parameters).toContain("IN_PROGRESS");
  });

  it("orders the result for bottleneck review by execution priority and planned timing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const workOrderSeq20 = {
      ...basePendingWorkOrder,
      id: "work-order-20",
      routingOperationSequenceNumber: 20,
    };
    mock.enqueueResults([baseActiveWorkCenter], [basePendingWorkOrder, workOrderSeq20]);

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

    expect(mock.selects[1].sql).toMatch(/order by .*"routingOperationSequenceNumber" asc/i);
  });

  it("returns summary fields with production-order reference operation sequence and progress totals", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveWorkCenter], [baseInProgressWorkOrder]);

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

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

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

  it("returns error when the work center does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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