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

export interface ActivateItemInput {
  id: string;
  from?: string[];
}

/**
 * Function: activateItem
 *
 * Transitions an item from DRAFT to ACTIVE status.
 * Requires name, SKU, and UoM to be set.
 */
export async function run(db: Transaction, input: ActivateItemInput) {
  const { id, from } = 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 valid for activation
  const validFromStatuses = from ?? ["DRAFT"];
  if (!validFromStatuses.includes(item.status)) {
    return err(new InvalidStateTransitionError(`${item.status} to ACTIVE`));
  }

  // 3. Update status to ACTIVE
  const activatedItem = await db
    .updateTable("Item")
    .set({ status: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ item: activatedItem });
}
