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

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

/**
 * Function: deactivateItem
 *
 * Transitions an item from ACTIVE to INACTIVE status,
 * preserving it for audit trails while preventing new transactions.
 */
export async function run(db: Transaction, input: DeactivateItemInput) {
  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 deactivation
  const validFromStatuses = from ?? ["ACTIVE"];
  if (!validFromStatuses.includes(item.status)) {
    return err(new InvalidStateTransitionError(`${item.status} to INACTIVE`));
  }

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

  return ok({ item: deactivatedItem });
}
