import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  RoutingNotFoundError,
  RoutingNotActivatableError,
  OperationRequiredError,
  DuplicateOperationSequenceError,
  WorkCenterNotActiveError,
  CrossCompanyWorkCenterError,
} from "../lib/errors.generated";
import {
  baseDraftRouting,
  baseActiveRouting,
  baseRoutingOperation,
  baseActiveWorkCenter,
  baseInactiveWorkCenter,
} from "../testing/fixtures";
import { run } from "./activateRouting";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

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

  it("activates a valid draft routing", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: RoutingOperation list
    spies.select.mockReturnValueOnce([baseRoutingOperation]);
    // select: WorkCenter lookup for operation
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // update: status to ACTIVE
    spies.update.mockReturnValue({ ...baseDraftRouting, status: "ACTIVE" });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("ACTIVE");
    }
    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, validInput, ctx);

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

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

    // select: Routing lookup - ACTIVE
    spies.select.mockReturnValueOnce(baseActiveRouting);

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

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

  it("returns error when the routing has no operations", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: RoutingOperation list - empty
    spies.select.mockReturnValueOnce([]);

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

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

  it("returns error when operation sequence numbers are duplicated", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: RoutingOperation list with duplicate sequences
    spies.select.mockReturnValueOnce([
      baseRoutingOperation,
      { ...baseRoutingOperation, id: "operation-dup", sequenceNumber: 10 },
    ]);

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

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

  it("returns error when a referenced work center is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: RoutingOperation list
    spies.select.mockReturnValueOnce([baseRoutingOperation]);
    // select: WorkCenter lookup - INACTIVE
    spies.select.mockReturnValueOnce(baseInactiveWorkCenter);

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

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

  it("returns error when a referenced work center is outside the routing company", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: RoutingOperation list
    spies.select.mockReturnValueOnce([baseRoutingOperation]);
    // select: WorkCenter lookup - different company
    spies.select.mockReturnValueOnce({
      ...baseActiveWorkCenter,
      companyId: "other-company",
    });

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

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