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 {
  MissingRequiredFieldError,
  DuplicateCodeError,
  ParentNotFoundError,
  MaxDepthExceededError,
} from "../lib/errors.generated";
import { baseRootCategory, baseChildCategory } from "../testing/fixtures";
import { run } from "./createProductCategory";

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

  const deps = { maxDepth: 3 };

  it("should return MissingRequiredFieldError when code is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const input = { code: "", name: "Clothing" };
    const result = await mock.withTx((trx) => run(trx, input, ctx, deps));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("should return MissingRequiredFieldError when name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const input = { code: "CLOTHING", name: "" };
    const result = await mock.withTx((trx) => run(trx, input, ctx, deps));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("should return DuplicateCodeError when code already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseRootCategory]);
    const input = { code: "CLOTHING", name: "Clothing" };
    const result = await mock.withTx((trx) => run(trx, input, ctx, deps));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateCodeError);
    }
  });

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

  it("should return MaxDepthExceededError when depth exceeds maxDepth", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [],
      [baseChildCategory],
      [{ parentId: "category-1" }],
      [{ parentId: null }],
    );
    const result = await mock.withTx((trx) =>
      run(trx, { code: "VNECKS", name: "V-Necks", parentId: baseChildCategory.id }, ctx, {
        maxDepth: 2,
      }),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MaxDepthExceededError);
    }
  });

  it("should create a root category when no parentId is provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newCategory = { ...baseRootCategory, id: "new-id" };
    mock.enqueueResults([], [newCategory]);

    const input = { code: "CLOTHING", name: "Clothing" };
    const result = await mock.withTx((trx) => run(trx, input, ctx, deps));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productCategory).toEqual(newCategory);
    }
  });

  it("should create a child category when parentId is provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newCategory = { ...baseChildCategory, id: "new-child-id" };
    mock.enqueueResults([], [baseRootCategory], [{ parentId: null }], [newCategory]);

    const input = {
      code: "TOPS",
      name: "Tops",
      parentId: baseRootCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input, ctx, deps));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productCategory).toEqual(newCategory);
    }
  });
});
