import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotReschedulableError,
  ExecutionAlreadyStartedError,
  InvalidDateRangeError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  basePendingWorkOrder,
  baseInProgressWorkOrder,
} from "../testing/fixtures";
import { run } from "./rescheduleProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const newStartDate = new Date("2024-04-01T00:00:00.000Z");
  const newEndDate = new Date("2024-04-15T00:00:00.000Z");

  it("reschedules a released order before execution starts", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rescheduled = {
      ...baseReleasedProductionOrder,
      plannedStartDate: newStartDate,
      plannedEndDate: newEndDate,
    };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // update
    spies.update.mockReturnValue(rescheduled);

    const result = await run(
      db,
      {
        id: baseReleasedProductionOrder.id,
        plannedStartDate: newStartDate,
        plannedEndDate: newEndDate,
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.plannedStartDate).toBe(newStartDate);
      expect(result.value.productionOrder.plannedEndDate).toBe(newEndDate);
    }
    expect(spies.update).toHaveBeenCalled();
  });

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

    const result = await run(
      db,
      { id: "nonexistent", plannedStartDate: newStartDate, plannedEndDate: newEndDate },
      ctx,
    );

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

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

    const result = await run(
      db,
      {
        id: baseDraftProductionOrder.id,
        plannedStartDate: newStartDate,
        plannedEndDate: newEndDate,
      },
      ctx,
    );

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

  it("returns error when execution has already started", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - one in progress
    spies.select.mockReturnValueOnce([baseInProgressWorkOrder]);

    const result = await run(
      db,
      {
        id: baseReleasedProductionOrder.id,
        plannedStartDate: newStartDate,
        plannedEndDate: newEndDate,
      },
      ctx,
    );

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

  it("returns error when planned dates are invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const invalidStart = new Date("2024-04-15T00:00:00.000Z");
    const invalidEnd = new Date("2024-04-01T00:00:00.000Z");

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);

    const result = await run(
      db,
      {
        id: baseReleasedProductionOrder.id,
        plannedStartDate: invalidStart,
        plannedEndDate: invalidEnd,
      },
      ctx,
    );

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

  it("preserves release snapshots after rescheduling", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rescheduled = {
      ...baseReleasedProductionOrder,
      plannedStartDate: newStartDate,
      plannedEndDate: newEndDate,
    };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // update
    spies.update.mockReturnValue(rescheduled);

    const result = await run(
      db,
      {
        id: baseReleasedProductionOrder.id,
        plannedStartDate: newStartDate,
        plannedEndDate: newEndDate,
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      // Status remains RELEASED - snapshots are preserved
      expect(result.value.productionOrder.selectedBomVersionId).toBe(
        baseReleasedProductionOrder.selectedBomVersionId,
      );
      expect(result.value.productionOrder.selectedRoutingRevisionId).toBe(
        baseReleasedProductionOrder.selectedRoutingRevisionId,
      );
    }
    // No delete calls should have been made
    expect(spies.delete).not.toHaveBeenCalled();
  });
});
