import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  WorkOrderNotFoundError,
  WorkOrderNotReportableError,
  InvalidReportedQuantityError,
  EmptyProgressTransactionError,
  ScrapHandoffRequiredError,
} from "../lib/errors.generated";
import { baseInProgressWorkOrder, basePendingWorkOrder } from "../testing/fixtures";
import { run } from "./reportWorkOrderProgress";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("reportWorkOrderProgress", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing:reportWorkOrderProgress"],
  };

  it("records partial completed quantity and time on an in-progress work order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedWorkOrder = {
      ...baseInProgressWorkOrder,
      completedQuantity: baseInProgressWorkOrder.completedQuantity + 10,
      actualRunTime: baseInProgressWorkOrder.actualRunTime + 30,
    };

    // work order lookup
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    // update work order
    spies.update.mockReturnValueOnce(updatedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);
    // select: parent order lookup for rollup
    spies.select.mockReturnValueOnce({ id: "production-order-2", status: "IN_PROGRESS" });

    const result = await run(
      db,
      { id: baseInProgressWorkOrder.id, completedQuantity: 10, actualRunTime: 30 },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.completedQuantity).toBe(
        baseInProgressWorkOrder.completedQuantity + 10,
      );
      expect(result.value.workOrder.actualRunTime).toBe(baseInProgressWorkOrder.actualRunTime + 30);
    }
    expect(spies.update).toHaveBeenCalled();
    expect(spies.insert).toHaveBeenCalled();
  });

  it("returns error when the work order does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent", completedQuantity: 5 }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(WorkOrderNotFoundError);
    }
  });

  it("returns error when the work order is not in progress", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePendingWorkOrder);

    const result = await run(db, { id: basePendingWorkOrder.id, completedQuantity: 5 }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(WorkOrderNotReportableError);
    }
  });

  it("returns error when completed or scrap quantity is negative", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { id: baseInProgressWorkOrder.id, completedQuantity: -5 }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidReportedQuantityError);
    }
  });

  it("returns error when no positive quantity or time is provided", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(
      db,
      { id: baseInProgressWorkOrder.id, completedQuantity: 0, scrapQuantity: 0 },
      ctx,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(EmptyProgressTransactionError);
    }
  });

  it("emits manufacturing scrap handoff when positive scrap is reported", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedWorkOrder = {
      ...baseInProgressWorkOrder,
      scrapQuantity: baseInProgressWorkOrder.scrapQuantity + 3,
      completedQuantity: baseInProgressWorkOrder.completedQuantity + 10,
    };

    // work order lookup
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    // update work order
    spies.update.mockReturnValueOnce(updatedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);
    // select: parent order lookup for rollup
    spies.select.mockReturnValueOnce({ id: "production-order-2", status: "IN_PROGRESS" });

    const result = await run(
      db,
      {
        id: baseInProgressWorkOrder.id,
        completedQuantity: 10,
        scrapQuantity: 3,
        scrapHandoffData: { reason: "defective material" },
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.scrapQuantity).toBe(baseInProgressWorkOrder.scrapQuantity + 3);
    }
  });

  it("returns error when positive scrap is reported without scrap handoff data", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // work order lookup
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);

    const result = await run(
      db,
      {
        id: baseInProgressWorkOrder.id,
        completedQuantity: 10,
        scrapQuantity: 3,
      },
      ctx,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ScrapHandoffRequiredError);
    }
  });

  it("rolls up execution progress to the parent order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedWorkOrder = {
      ...baseInProgressWorkOrder,
      completedQuantity: baseInProgressWorkOrder.completedQuantity + 20,
      actualSetupTime: baseInProgressWorkOrder.actualSetupTime + 5,
      actualRunTime: baseInProgressWorkOrder.actualRunTime + 45,
    };

    // work order lookup
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    // update work order
    spies.update.mockReturnValueOnce(updatedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);
    // select: parent order lookup for rollup
    spies.select.mockReturnValueOnce({ id: "production-order-2", status: "IN_PROGRESS" });

    const result = await run(
      db,
      {
        id: baseInProgressWorkOrder.id,
        completedQuantity: 20,
        actualSetupTime: 5,
        actualRunTime: 45,
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.completedQuantity).toBe(
        baseInProgressWorkOrder.completedQuantity + 20,
      );
      expect(result.value.workOrder.actualSetupTime).toBe(
        baseInProgressWorkOrder.actualSetupTime + 5,
      );
      expect(result.value.workOrder.actualRunTime).toBe(baseInProgressWorkOrder.actualRunTime + 45);
    }
    // Verify parent production order was updated (rollup)
    expect(spies.update).toHaveBeenCalledTimes(2);
    expect(spies.select).toHaveBeenCalledTimes(2);
  });
});
