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 {
  RoutingNotFoundError,
  RoutingNotMutableError,
  DuplicateOperationSequenceError,
  InvalidStandardTimeError,
  WorkCenterNotFoundError,
  CrossCompanyWorkCenterError,
} from "../lib/errors.generated";
import { baseDraftRouting, baseActiveRouting, baseActiveWorkCenter } from "../testing/fixtures";
import { run } from "./updateRouting";

describe("updateRouting", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing: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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftRouting],
      [baseActiveWorkCenter],
      [baseActiveWorkCenter],
      [],
      [
        {
          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 mock.withTx((trx) => run(trx, validInput, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing).toBeDefined();
    }
    // No header-field changes were requested, so the header UPDATE is skipped.
    expect(mock.deletes.length).toBeGreaterThan(0);
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

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

    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseActiveRouting]);

    const result = await mock.withTx((trx) => run(trx, { ...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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftRouting]);

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

    const result = await mock.withTx((trx) =>
      run(trx, { ...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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftRouting]);

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

    const result = await mock.withTx((trx) => run(trx, { ...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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftRouting], []);

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftRouting],
      [{ ...baseActiveWorkCenter, companyId: "other-company" }],
    );

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

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

  it("preserves released routing snapshots after update", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftRouting],
      [baseActiveWorkCenter],
      [],
      [
        {
          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 mock.withTx((trx) =>
      run(trx, { ...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");
    }
  });
});
