import { Transaction } from "../generated/kysely-tailordb";
import { DeleteNonDraftError, ItemNotFoundError } from "../lib/errors.generated";
import { ok, err } from "@tailor-platform/erp-kit/module";

export interface DeleteItemInput {
  id: string;
}

/**
 * Function: deleteItem
 *
 * Permanently removes a DRAFT item from the system.
 * Only DRAFT items can be deleted; ACTIVE and INACTIVE are preserved for audit trails.
 */
export async function run(db: Transaction, input: DeleteItemInput) {
  const { id } = input;

  // 1. Check item exists
  const item = await db
    .selectFrom("Item")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!item) {
    return err(new ItemNotFoundError(id));
  }

  // 2. Check status is DRAFT
  if (item.status !== "DRAFT") {
    return err(new DeleteNonDraftError(`${id} (status: ${item.status})`));
  }

  // 3. Remove taxonomy assignments
  await db.deleteFrom("ItemTaxonomyAssignment").where("itemId", "=", id).execute();

  // 4. Delete item
  await db.deleteFrom("Item").where("id", "=", id).execute();

  return ok({ success: true as const });
}
