import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  WorkCenterNotFoundError,
  WorkCenterNotDeactivatableError,
  WorkCenterInUseError,
} from "../lib/errors.generated";
import { baseActiveWorkCenter, baseDraftWorkCenter } from "../testing/fixtures";
import { run } from "./deactivateWorkCenter";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("deactivates an active work center with no blocking dependencies", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivated = { ...baseActiveWorkCenter, status: "INACTIVE" as const };

    spies.select.mockReturnValueOnce(baseActiveWorkCenter); // fetch work center
    spies.select.mockReturnValueOnce(undefined); // no active routing dependency
    spies.select.mockReturnValueOnce(undefined); // no open work orders
    spies.update.mockReturnValue(deactivated);

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

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

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

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

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

  it("returns error when the work center is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftWorkCenter);

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

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

  it("returns error when open routing or released-work dependencies block deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseActiveWorkCenter); // fetch work center
    spies.select.mockReturnValueOnce({ id: "operation-1" }); // active routing dependency found

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

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

  it("returns error when open work orders block deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseActiveWorkCenter); // fetch work center
    spies.select.mockReturnValueOnce(undefined); // no active routing dependency
    spies.select.mockReturnValueOnce({ id: "work-order-1" }); // open work order found

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

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

  it("preserves historical work-order and cost data after deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivated = {
      ...baseActiveWorkCenter,
      status: "INACTIVE" as const,
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    spies.select.mockReturnValueOnce(undefined); // no active routing dependency
    spies.select.mockReturnValueOnce(undefined); // no open work orders
    spies.update.mockReturnValue(deactivated);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      // The work center is deactivated but its identity and historical fields are preserved
      expect(result.value.workCenter.id).toBe(baseActiveWorkCenter.id);
      expect(result.value.workCenter.code).toBe(baseActiveWorkCenter.code);
      expect(result.value.workCenter.status).toBe("INACTIVE");
    }
  });
});
