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 {
  WorkCenterNotFoundError,
  WorkCenterNotDeactivatableError,
  WorkCenterInUseError,
} from "../lib/errors.generated";
import { baseActiveWorkCenter, baseDraftWorkCenter } from "../testing/fixtures";
import { run } from "./deactivateWorkCenter";

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

  it("deactivates an active work center with no blocking dependencies", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivated = { ...baseActiveWorkCenter, status: "INACTIVE" as const };

    mock.enqueueResults([baseActiveWorkCenter], [], [], [deactivated]);

    const result = await mock.withTx((trx) => run(trx, { id: baseActiveWorkCenter.id }, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workCenter.status).toBe("INACTIVE");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

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

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

    mock.enqueueResults([baseActiveWorkCenter], [{ id: "operation-1" }]);

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

    mock.enqueueResults([baseActiveWorkCenter], [], [{ id: "work-order-1" }]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const deactivated = {
      ...baseActiveWorkCenter,
      status: "INACTIVE" as const,
      updatedAt: new Date(),
    };

    mock.enqueueResults([baseActiveWorkCenter], [], [], [deactivated]);

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