import { executeTransition, ok } from "@tailor-platform/erp-kit/core";
import { userLifecycle } from "../db/user.lifecycle.generated";
import { Transaction } from "../generated/kysely-tailordb";
import { InvalidStatusTransitionError, UserNotFoundError } from "../lib/errors.generated";
import { recomputeUserPermissions } from "../lib/recomputeUserPermissions";

export interface ActivateUserInput {
  userId: string;
}

/**
 * Function: activateUser
 *
 * Transitions a user from PENDING to ACTIVE status.
 * Only PENDING users can be activated; use reactivateUser for INACTIVE users.
 */
export async function run(db: Transaction, input: ActivateUserInput) {
  const result = await executeTransition({
    db,
    tableName: "User",
    statusField: "status",
    id: input.userId,
    transition: "activate",
    lifecycle: userLifecycle,
    errors: { notFound: UserNotFoundError, invalidTransition: InvalidStatusTransitionError },
  });
  if (!result.ok) return result;
  const user = await recomputeUserPermissions(db, input.userId);
  return ok({ user });
}
