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,
  ProductionOrderNotUnreleasableError,
  ExecutionAlreadyStartedError,
  InventoryHandoffExistsError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseMaterialRequirement,
  baseCollectingCostSummary,
} from "../testing/fixtures";
import { run } from "./unreleaseProductionOrder";

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

  it("unreleases a released order with no execution evidence", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const draftOrder = { ...baseReleasedProductionOrder, status: "DRAFT" as const };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [baseMaterialRequirement],
      [baseCollectingCostSummary],
      [],
      [],
      [],
      [],
      [],
      [],
      [draftOrder],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("DRAFT");
    }
    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 RELEASED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProductionOrder]);

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

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

  it("returns error when a work order has already started", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseReleasedProductionOrder], [baseInProgressWorkOrder]);

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

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

  it("returns error when inventory handoff evidence already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const costSummaryWithActuals = {
      ...baseCollectingCostSummary,
      actualMaterialCost: 500,
    };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [baseMaterialRequirement],
      [costSummaryWithActuals],
    );

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

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

  it("removes work orders and material requirements when unrelease succeeds", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const draftOrder = { ...baseReleasedProductionOrder, status: "DRAFT" as const };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [],
      [baseCollectingCostSummary],
      [],
      [],
      [],
      [],
      [],
      [],
      [draftOrder],
    );

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

    expect(result.ok).toBe(true);
    expect(mock.deletes.length).toBeGreaterThan(0);
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
