import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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";

describe("rescheduleProductionOrder", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing: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 mock = createKyselyMock<Namespace["main-db"]>();
    const rescheduled = {
      ...baseReleasedProductionOrder,
      plannedStartDate: newStartDate,
      plannedEndDate: newEndDate,
    };

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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(mock.updates.length).toBeGreaterThan(0);
  });

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

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

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

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    const invalidStart = new Date("2024-04-15T00:00:00.000Z");
    const invalidEnd = new Date("2024-04-01T00:00:00.000Z");

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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 mock = createKyselyMock<Namespace["main-db"]>();
    const rescheduled = {
      ...baseReleasedProductionOrder,
      plannedStartDate: newStartDate,
      plannedEndDate: newEndDate,
    };

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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(mock.deletes).toHaveLength(0);
  });
});
