import { ok, err } from "@tailor-platform/erp-kit/core";
import { Transaction } from "../generated/kysely-tailordb";
import { ProductNotFoundError, CategoryNotFoundError } from "../lib/errors.generated";

export interface AssignProductToCategoryInput {
  productId: string;
  categoryId: string;
}

/**
 * Function: assignProductToCategory
 *
 * Assigns a product to a category. Idempotent.
 */
export async function run(db: Transaction, input: AssignProductToCategoryInput) {
  const { productId, categoryId } = input;

  // Validate product exists
  const product = await db
    .selectFrom("Product")
    .select("id")
    .where("id", "=", productId)
    .executeTakeFirst();
  if (!product) {
    return err(new ProductNotFoundError(productId));
  }

  // Validate category exists
  const category = await db
    .selectFrom("ProductCategory")
    .select("id")
    .where("id", "=", categoryId)
    .executeTakeFirst();
  if (!category) {
    return err(new CategoryNotFoundError(categoryId));
  }

  // Check if already assigned (idempotent, with lock for uniqueness)
  const existing = await db
    .selectFrom("ProductCategoryAssignment")
    .selectAll()
    .where("productId", "=", productId)
    .where("categoryId", "=", categoryId)
    .forUpdate()
    .executeTakeFirst();
  if (existing) {
    return ok({ productCategoryAssignment: existing });
  }

  const assignment = await db
    .insertInto("ProductCategoryAssignment")
    .values({
      productId,
      categoryId,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ productCategoryAssignment: assignment });
}
