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 {
  RoutingItemNotFoundError,
  OperationRequiredError,
  DuplicateOperationSequenceError,
  InvalidStandardTimeError,
  WorkCenterNotFoundError,
  CrossCompanyWorkCenterError,
} from "../lib/errors.generated";
import { baseDraftRouting, baseActiveWorkCenter, baseItem } from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./createRouting";

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

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("DRAFT");
      expect(result.value.routing.parentItemId).toBe("item-1");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("returns error when no operations are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

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

    const result = await mock.withTx((trx) =>
      run(trx, { ...validInput, operations: duplicateOps }, ctx, mockItemQueries([baseItem])),
    );

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

  it("returns error when a standard time is negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

    const result = await mock.withTx((trx) =>
      run(trx, { ...validInput, operations: badOps }, ctx, mockItemQueries([baseItem])),
    );

    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([]);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

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

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

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

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

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

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