import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotMutableError,
  InvalidPlannedQuantityError,
  ImmutableScopeFieldError,
  CrossScopeMasterReferenceError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  baseActiveBom,
} from "../testing/fixtures";
import { run } from "./updateProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("updates draft planning fields on a production order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftProductionOrder, plannedQuantity: 200 };

    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    spies.update.mockReturnValue(updated);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.plannedQuantity).toBe(200);
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("returns error when the order 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(ProductionOrderNotFoundError);
    }
  });

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

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

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

  it("returns error when planned quantity is not positive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);

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

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

  it("returns error when immutable scope identity is changed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);

    const result = await run(
      db,
      { id: baseDraftProductionOrder.id, orderedItemId: "different-item" },
      ctx,
    );

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

  it("returns error when BOM or routing references are out of scope", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const crossScopeBom = { ...baseActiveBom, companyId: "other-company" };

    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom lookup
    spies.select.mockReturnValueOnce(crossScopeBom);

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

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