import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import { Transaction } from "../generated/kysely-tailordb";
import {
  DuplicateCodeError,
  MissingRequiredFieldError,
  ParentNotFoundError,
  MaxDepthExceededError,
} from "../lib/errors.generated";
import { calculateCategoryDepth } from "../query/calculateCategoryDepth.generated";

export interface CreateProductCategoryInput {
  code: string;
  name: string;
  parentId?: string;
}

/**
 * Function: createProductCategory
 *
 * Creates a new category node in the product category tree.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreateProductCategoryInput & CF,
  ctx: CommandContext,
  deps: { maxDepth: number },
) {
  const { maxDepth } = deps;
  const { code, name, parentId, ...customFields } = input;

  if (!code?.trim()) {
    return err(new MissingRequiredFieldError("code"));
  }
  if (!name?.trim()) {
    return err(new MissingRequiredFieldError("name"));
  }

  // Check code uniqueness
  const existing = await db
    .selectFrom("ProductCategory")
    .select("id")
    .where("code", "=", code)
    .forUpdate()
    .executeTakeFirst();
  if (existing) {
    return err(new DuplicateCodeError(code));
  }

  // If parent specified, check it exists and validate depth
  if (parentId) {
    const parent = await db
      .selectFrom("ProductCategory")
      .select("id")
      .where("id", "=", parentId)
      .executeTakeFirst();
    if (!parent) {
      return err(new ParentNotFoundError(parentId));
    }

    const depthResult = await calculateCategoryDepth(db, { categoryId: parentId }, ctx);
    if (!depthResult.ok) return err(new ParentNotFoundError(parentId));
    const depth = depthResult.value.depth + 1;
    if (depth > maxDepth) {
      return err(new MaxDepthExceededError(`${depth} exceeds ${maxDepth}`));
    }
  }

  const category = await db
    .insertInto("ProductCategory")
    .values({
      ...(customFields as Record<string, unknown>),
      code,
      name,
      parentId: parentId ?? null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ productCategory: category });
}
