import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  RoutingNotFoundError,
  RoutingNotDeactivatableError,
  ReplacementRequiredError,
} from "../lib/errors.generated";
import {
  baseActiveRouting,
  baseDraftRouting,
  baseReleasedProductionOrder,
} from "../testing/fixtures";
import { run } from "./deactivateRouting";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const validInput = { id: "routing-2" };

  it("deactivates an active routing", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseActiveRouting);
    // select: Replacement routing lookup - another active routing exists
    spies.select.mockReturnValueOnce({ ...baseActiveRouting, id: "routing-4" });
    // update: status to INACTIVE
    spies.update.mockReturnValue({ ...baseActiveRouting, status: "INACTIVE" });

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("INACTIVE");
    }
    expect(spies.update).toHaveBeenCalled();
  });

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

    // select: Routing lookup - not found
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("returns error when the routing is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup - DRAFT
    spies.select.mockReturnValueOnce(baseDraftRouting);

    const result = await run(db, { id: "routing-1" }, ctx);

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

  it("returns error when replacement policy blocks deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseActiveRouting);
    // select: Replacement routing lookup - no replacement found
    spies.select.mockReturnValueOnce(undefined);
    // select: Dependent production order - exists in RELEASED
    spies.select.mockReturnValueOnce({
      ...baseReleasedProductionOrder,
      selectedRoutingRevisionId: "routing-2",
    });

    const result = await run(db, validInput, ctx);

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

  it("preserves released operation snapshots after deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseActiveRouting);
    // select: Replacement routing exists
    spies.select.mockReturnValueOnce({ ...baseActiveRouting, id: "routing-4" });
    // update: status to INACTIVE
    spies.update.mockReturnValue({ ...baseActiveRouting, status: "INACTIVE" });

    const result = await run(db, validInput, ctx);

    // Deactivation only updates the Routing status,
    // not ProductionOrderRoutingSnapshot, preserving frozen snapshots.
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("INACTIVE");
    }
  });
});
