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 {
  ProductionOrderNotFoundError,
  ProductionOrderNotMutableError,
  InvalidPlannedQuantityError,
  CrossScopeMasterReferenceError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  baseActiveBom,
} from "../testing/fixtures";
import { run } from "./updateProductionOrder";

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

  it("updates draft planning fields on a production order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseDraftProductionOrder, plannedQuantity: 200 };

    mock.enqueueResults([baseDraftProductionOrder], [updated]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.plannedQuantity).toBe(200);
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

  it("returns error when the order is not in DRAFT", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseReleasedProductionOrder]);

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

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

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

  it("returns error when BOM or routing references are out of scope", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const crossScopeBom = { ...baseActiveBom, companyId: "other-company" };

    mock.enqueueResults([baseDraftProductionOrder], [crossScopeBom]);

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

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