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

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

  const validOperations = [
    {
      sequenceNumber: 10,
      operationDescription: "Revised assembly",
      workCenterId: "work-center-2",
      standardSetupTime: 25,
      standardRunTime: 55,
      operatorInstructions: null,
    },
    {
      sequenceNumber: 20,
      operationDescription: "Revised QC",
      workCenterId: "work-center-2",
      standardSetupTime: 15,
      standardRunTime: 20,
      operatorInstructions: null,
    },
  ];

  const validInput = {
    id: "routing-1",
    operations: validOperations,
  };

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

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: WorkCenter lookup for op 1
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // select: WorkCenter lookup for op 2
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // update: Routing header
    spies.update.mockReturnValue({ ...baseDraftRouting, updatedAt: new Date() });
    // insert: new operations
    spies.insert.mockReturnValue({
      id: "op-new",
      routingId: "routing-1",
      sequenceNumber: 10,
      operationDescription: "Revised assembly",
      workCenterId: "work-center-2",
      standardSetupTime: 25,
      standardRunTime: 55,
      operatorInstructions: null,
      createdAt: new Date(),
      updatedAt: null,
    });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing).toBeDefined();
    }
    expect(spies.update).toHaveBeenCalled();
  });

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

    // select: Routing 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(RoutingNotFoundError);
    }
  });

  it("returns error when the routing is not in DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup - ACTIVE
    spies.select.mockReturnValueOnce(baseActiveRouting);

    const result = await run(db, { ...validInput, id: "routing-2" }, ctx);

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

  it("returns error when revised sequence numbers conflict", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);

    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 revised standard time is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);

    const badOps = [{ ...validOperations[0], standardRunTime: -1 }];

    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: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // 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 referenced work center is outside the routing company", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // 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("preserves released routing snapshots after update", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: Routing lookup - DRAFT (only DRAFT can be updated)
    spies.select.mockReturnValueOnce(baseDraftRouting);
    // select: WorkCenter lookup for op 1
    spies.select.mockReturnValueOnce(baseActiveWorkCenter);
    // update: Routing header
    spies.update.mockReturnValue({ ...baseDraftRouting, updatedAt: new Date() });
    // insert: new operations
    spies.insert.mockReturnValue({
      id: "op-new",
      routingId: "routing-1",
      sequenceNumber: 10,
      operationDescription: "Revised assembly",
      workCenterId: "work-center-2",
      standardSetupTime: 25,
      standardRunTime: 55,
      operatorInstructions: null,
      createdAt: new Date(),
      updatedAt: null,
    });

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

    // The update only touches the Routing and RoutingOperation tables,
    // not ProductionOrderRoutingSnapshot, preserving frozen snapshots.
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("DRAFT");
    }
  });
});
