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 {
  ProductionItemNotFoundError,
  ProductionItemNotManufacturableError,
  InvalidPlannedQuantityError,
  InvalidSiteScopeError,
  CrossScopeMasterReferenceError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseActiveBom,
  baseActiveRouting,
  baseItem,
  baseSite,
} from "../testing/fixtures";
import { mockItemQueries, mockOrgQueries } from "../testing/moduleMocks";
import { run } from "./createProductionOrder";

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

  const validInput = {
    orderedItemId: "item-1",
    companyId: "company-1",
    siteId: "site-1",
    plannedQuantity: 100,
    plannedStartDate: new Date("2024-03-01T00:00:00.000Z"),
    plannedEndDate: new Date("2024-03-15T00:00:00.000Z"),
  };

  it("creates a draft production order for a manufacturable item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdOrder = {
      ...baseDraftProductionOrder,
      id: "new-order-id",
    };

    mock.enqueueResults([createdOrder]);

    const result = await mock.withTx((trx) =>
      run(trx, validInput, ctx, mockItemQueries([baseItem]), mockOrgQueries(baseSite)),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("DRAFT");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("returns error when the produced item does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, validInput, ctx, mockItemQueries([]), mockOrgQueries(baseSite)),
    );

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

  it("returns error when the produced item is not manufacturable", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        validInput,
        ctx,
        mockItemQueries([{ ...baseItem, isManufacturable: false }]),
        mockOrgQueries(baseSite),
      ),
    );

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

  it("returns error when planned quantity is not positive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...validInput, plannedQuantity: 0 },
        ctx,
        mockItemQueries([baseItem]),
        mockOrgQueries(baseSite),
      ),
    );

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

  it("returns error when site scope is inconsistent with company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...validInput, siteId: "" },
        ctx,
        mockItemQueries([baseItem]),
        mockOrgQueries(baseSite),
      ),
    );

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

  it("returns error when site does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, validInput, ctx, mockItemQueries([baseItem]), mockOrgQueries(null)),
    );

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

  it("returns error when an optional BOM reference is outside scope", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const crossScopeBom = { ...baseActiveBom, companyId: "other-company" };

    mock.enqueueResults([crossScopeBom]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...validInput, selectedBomVersionId: crossScopeBom.id },
        ctx,
        mockItemQueries([baseItem]),
        mockOrgQueries(baseSite),
      ),
    );

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

  it("returns error when an optional routing reference is outside scope", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const crossScopeRouting = { ...baseActiveRouting, companyId: "other-company" };

    mock.enqueueResults([crossScopeRouting]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...validInput, selectedRoutingRevisionId: crossScopeRouting.id },
        ctx,
        mockItemQueries([baseItem]),
        mockOrgQueries(baseSite),
      ),
    );

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