import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotReleasableError,
  BomNotResolvedError,
  RoutingNotResolvedError,
  CrossCompanyMasterReferenceError,
  CrossSiteMasterReferenceError,
  PlannedMaterialCostUnavailableError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  baseActiveBom,
  baseActiveRouting,
  baseBomLine,
  baseRoutingOperation,
  baseActiveWorkCenter,
} from "../testing/fixtures";
import { run } from "./releaseProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

const baseReleaseValuation = {
  id: "item-2",
  valuationMethod: "AVCO",
  costPerUnit: 10,
  currencyCode: "USD",
  valuationReference: "valuation-1",
};

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

  it("releases a draft order with valid BOM and routing snapshots", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const released = { ...baseDraftProductionOrder, status: "RELEASED" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution (no selectedBomVersionId, so default resolution)
    spies.select.mockReturnValueOnce(baseActiveBom);
    // routing resolution (no selectedRoutingRevisionId, so default resolution)
    spies.select.mockReturnValueOnce(baseActiveRouting);
    // BOM lines query
    spies.select.mockReturnValueOnce([baseBomLine]);
    // material cost valuation for bomLine itemId
    spies.select.mockReturnValueOnce(baseReleaseValuation);
    // routing operations query
    spies.select.mockReturnValueOnce([baseRoutingOperation]);
    // work center lookup for operation
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // inserts: bom snapshot, routing snapshot, cost baseline, material requirement, work order, cost summary
    spies.insert.mockReturnValue({});
    // update: order status
    spies.update.mockReturnValue(released);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("RELEASED");
    }
    const snapshotValues = spies.values.mock.calls.find(
      ([values]) =>
        typeof values === "object" &&
        values !== null &&
        "snapshotData" in (values as Record<string, unknown>),
    )?.[0] as Record<string, unknown> | undefined;
    expect(snapshotValues?.snapshotData).not.toBeNull();
  });

  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 }, ctx);

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

  it("returns error when no active BOM can be resolved", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution returns nothing
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("returns error when no active routing can be resolved", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution
    spies.select.mockReturnValueOnce(baseActiveBom);
    // routing resolution returns nothing
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("returns error when BOM or routing belongs to another company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const crossCompanyBom = { ...baseActiveBom, companyId: "other-company" };

    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution
    spies.select.mockReturnValueOnce(crossCompanyBom);

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

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

  it("returns error when BOM or routing belongs to another site in the same company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const crossSiteBom = { ...baseActiveBom, companyId: "company-1", siteId: "other-site" };

    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution
    spies.select.mockReturnValueOnce(crossSiteBom);

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

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

  it("returns error when inventory valuation for a required component is unavailable", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution
    spies.select.mockReturnValueOnce(baseActiveBom);
    // routing resolution
    spies.select.mockReturnValueOnce(baseActiveRouting);
    // BOM lines query
    spies.select.mockReturnValueOnce([baseBomLine]);
    // material cost valuation returns nothing
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("creates work orders and a collecting cost summary at release", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const released = {
      ...baseDraftProductionOrder,
      status: "RELEASED" as const,
      selectedBomVersionId: baseActiveBom.id,
      selectedRoutingRevisionId: baseActiveRouting.id,
    };

    // order lookup
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // bom resolution
    spies.select.mockReturnValueOnce(baseActiveBom);
    // routing resolution
    spies.select.mockReturnValueOnce(baseActiveRouting);
    // BOM lines query
    spies.select.mockReturnValueOnce([baseBomLine]);
    // material cost valuation
    spies.select.mockReturnValueOnce(baseReleaseValuation);
    // routing operations query
    spies.select.mockReturnValueOnce([baseRoutingOperation]);
    // work center lookup
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // inserts
    spies.insert.mockReturnValue({});
    // update
    spies.update.mockReturnValue(released);

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

    expect(result.ok).toBe(true);
    // Verify inserts were called: bom snapshot + routing snapshot + cost baseline +
    // material requirements + work orders + cost summary
    expect(spies.insert).toHaveBeenCalled();
    expect(spies.update).toHaveBeenCalled();
  });
});
