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 {
  CategoryNotFoundError,
  ParentNotFoundError,
  CircularReferenceError,
  MaxDepthExceededError,
} from "../lib/errors.generated";
import { baseRootCategory, baseChildCategory, baseLeafCategory } from "../testing/fixtures";
import type { MoveProductCategoryInput } from "./moveProductCategory";
import { run } from "./moveProductCategory";

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

  const config = { maxDepth: 3 };

  it("should return CategoryNotFoundError when category does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const input: MoveProductCategoryInput = {
      id: "non-existent",
      newParentId: baseRootCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, config));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CategoryNotFoundError);
    }
  });

  it("should return ParentNotFoundError when new parent does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChildCategory], []);
    const input: MoveProductCategoryInput = {
      id: baseChildCategory.id,
      newParentId: "non-existent",
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, config));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ParentNotFoundError);
    }
  });

  it("should return CircularReferenceError when move would create a cycle", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseRootCategory],
      [baseLeafCategory],
      [{ parentId: "category-2" }],
      [{ parentId: "category-1" }],
    );

    const input: MoveProductCategoryInput = {
      id: baseRootCategory.id,
      newParentId: baseLeafCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, config));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CircularReferenceError);
    }
  });

  it("should return MaxDepthExceededError when move would exceed max depth", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseLeafCategory],
      [baseChildCategory],
      [{ parentId: "category-1" }],
      [{ parentId: null }],
      [{ parentId: "category-1" }],
      [{ parentId: null }],
      [],
    );

    const input: MoveProductCategoryInput = {
      id: baseLeafCategory.id,
      newParentId: baseChildCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, { maxDepth: 2 }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MaxDepthExceededError);
    }
  });

  it("should move category to new parent successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const movedCategory = {
      ...baseLeafCategory,
      parentId: baseRootCategory.id,
      updatedAt: new Date(),
    };
    mock.enqueueResults(
      [baseLeafCategory],
      [baseRootCategory],
      [{ parentId: null }],
      [{ parentId: null }],
      [],
      [movedCategory],
    );

    const input: MoveProductCategoryInput = {
      id: baseLeafCategory.id,
      newParentId: baseRootCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, config));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.category.parentId).toBe(baseRootCategory.id);
    }
  });

  it("should promote category to root when newParentId is null", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const movedCategory = { ...baseChildCategory, parentId: null, updatedAt: new Date() };
    mock.enqueueResults([baseChildCategory], [movedCategory]);

    const input: MoveProductCategoryInput = {
      id: baseChildCategory.id,
      newParentId: null,
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, config));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.category.parentId).toBeNull();
    }
  });
});
