import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionItemNotFoundError,
  ProductionItemNotManufacturableError,
  InvalidPlannedQuantityError,
  InvalidSiteScopeError,
  CrossScopeMasterReferenceError,
} from "../lib/errors.generated";
import { baseDraftProductionOrder, baseActiveBom, baseActiveRouting } from "../testing/fixtures";
import { run } from "./createProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("createProductionOrder", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["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 { db, spies } = createMockDb<Transaction>();
    const createdOrder = {
      ...baseDraftProductionOrder,
      id: "new-order-id",
    };

    // item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // site lookup
    spies.select.mockReturnValueOnce({ id: "site-1" });
    // insert
    spies.insert.mockReturnValue(createdOrder);

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("DRAFT");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("returns error when the produced item does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // item lookup returns undefined
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, validInput, ctx);

    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 { db, spies } = createMockDb<Transaction>();

    // item exists but not manufacturable
    spies.select.mockReturnValueOnce({ id: "item-1", isManufacturable: false });

    const result = await run(db, validInput, ctx);

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

  it("returns error when planned quantity is not positive", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { ...validInput, plannedQuantity: 0 }, ctx);

    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 { db } = createMockDb<Transaction>();

    const result = await run(db, { ...validInput, siteId: "" }, ctx);

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

  it("returns error when site does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // site lookup returns undefined
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, validInput, ctx);

    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 { db, spies } = createMockDb<Transaction>();
    const crossScopeBom = { ...baseActiveBom, companyId: "other-company" };

    // item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // site lookup
    spies.select.mockReturnValueOnce({ id: "site-1" });
    // bom lookup
    spies.select.mockReturnValueOnce(crossScopeBom);

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

    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 { db, spies } = createMockDb<Transaction>();
    const crossScopeRouting = { ...baseActiveRouting, companyId: "other-company" };

    // item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // site lookup
    spies.select.mockReturnValueOnce({ id: "site-1" });
    // routing lookup
    spies.select.mockReturnValueOnce(crossScopeRouting);

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

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