import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  RoutingItemNotFoundError,
  OperationRequiredError,
  DuplicateOperationSequenceError,
  InvalidStandardTimeError,
  WorkCenterNotFoundError,
  CrossCompanyWorkCenterError,
} from "../lib/errors.generated";
import { baseDraftRouting, baseActiveWorkCenter } from "../testing/fixtures";
import { run } from "./createRouting";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const validOperations = [
    {
      sequenceNumber: 10,
      operationDescription: "Assembly step",
      workCenterId: "work-center-2",
      standardSetupTime: 30,
      standardRunTime: 60,
      operatorInstructions: null,
    },
    {
      sequenceNumber: 20,
      operationDescription: "Quality check",
      workCenterId: "work-center-2",
      standardSetupTime: 10,
      standardRunTime: 15,
      operatorInstructions: null,
    },
  ];

  const validInput = {
    parentItemId: "item-1",
    companyId: "company-1",
    siteId: null,
    revisionNumber: "R1",
    operations: validOperations,
  };

  it("creates a draft routing with ordered operations", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // select: WorkCenter lookup for op 1
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // select: WorkCenter lookup for op 2
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // insert: Routing
    spies.insert.mockReturnValue(baseDraftRouting);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("DRAFT");
      expect(result.value.routing.parentItemId).toBe("item-1");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("returns error when no operations are provided", async () => {
    const { db, spies } = createMockDb<Transaction>();

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

    const result = await run(db, { ...validInput, operations: [] }, ctx);

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

  it("returns error when two operations share the same sequence", async () => {
    const { db, spies } = createMockDb<Transaction>();

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

    const duplicateOps = [
      { ...validOperations[0], sequenceNumber: 10 },
      { ...validOperations[1], sequenceNumber: 10 },
    ];

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

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

  it("returns error when a standard time is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();

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

    const badOps = [{ ...validOperations[0], standardSetupTime: -5 }];

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

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

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

    // select: Item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // select: WorkCenter lookup - not found
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("returns error when a work center is outside the routing company", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Item lookup
    spies.select.mockReturnValueOnce({ id: "item-1" });
    // select: WorkCenter lookup - different company
    spies.select.mockReturnValueOnce({
      ...baseActiveWorkCenter,
      companyId: "other-company",
    });

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

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

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

    // select: Item lookup - not found
    spies.select.mockReturnValueOnce(undefined);

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

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