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

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

/**
 * Function: reactivateItem
 *
 * Transitions an item from INACTIVE back to ACTIVE status,
 * restoring a previously discontinued SKU for transactions.
 */
export async function run(db: Transaction, input: ReactivateItemInput) {
  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 reactivation
  const validFromStatuses = from ?? ["INACTIVE"];
  if (!validFromStatuses.includes(item.status)) {
    return err(new InvalidStateTransitionError(`${item.status} to ACTIVE`));
  }

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

  return ok({ item: reactivatedItem! });
}
