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,
  ProductionOrderNotReleasableError,
  BomNotResolvedError,
  RoutingNotResolvedError,
  CrossCompanyMasterReferenceError,
  CrossSiteMasterReferenceError,
  PlannedMaterialCostUnavailableError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  baseActiveBom,
  baseActiveRouting,
  baseBomLine,
  baseRoutingOperation,
  baseActiveWorkCenter,
  baseItem,
} from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./releaseProductionOrder";

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

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

  it("releases a draft order with valid BOM and routing snapshots", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const released = { ...baseDraftProductionOrder, status: "RELEASED" as const };

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("RELEASED");
    }
    const snapshotValues = mock.inserts
      .flatMap((insert) => insert.insertRows())
      .find((row) => "snapshotData" in row);
    expect(snapshotValues?.snapshotData).not.toBeNull();
  });

  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, mockItemQueries([])),
    );

    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 }, ctx, mockItemQueries([])),
    );

    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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProductionOrder], []);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProductionOrder], [baseActiveBom], []);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();
    const crossCompanyBom = { ...baseActiveBom, companyId: "other-company" };

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

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

    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 mock = createKyselyMock<Namespace["main-db"]>();
    const crossSiteBom = { ...baseActiveBom, companyId: "company-1", siteId: "other-site" };

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

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftProductionOrder],
      [baseActiveBom],
      [baseActiveRouting],
      [baseBomLine],
    );

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

    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 mock = createKyselyMock<Namespace["main-db"]>();
    const released = {
      ...baseDraftProductionOrder,
      status: "RELEASED" as const,
      selectedBomVersionId: baseActiveBom.id,
      selectedRoutingRevisionId: baseActiveRouting.id,
    };

    mock.enqueueResults(
      [baseDraftProductionOrder],
      [baseActiveBom],
      [baseActiveRouting],
      [baseBomLine],
      [baseRoutingOperation],
      [baseActiveWorkCenter],
      [{}],
      [{}],
      [{}],
      [{}],
      [{}],
      [{}],
      [released],
    );

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

    expect(result.ok).toBe(true);
    // Verify inserts were called: bom snapshot + routing snapshot + cost baseline +
    // material requirements + work orders + cost summary
    expect(mock.inserts.length).toBeGreaterThan(0);
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
