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 ReactivateUserInput {
  userId: string;
}

/**
 * Function: reactivateUser
 *
 * Transitions a user from INACTIVE back to ACTIVE status.
 * Restores access for previously deactivated users.
 */
export async function run(db: Transaction, input: ReactivateUserInput) {
  const result = await executeTransition({
    db,
    tableName: "User",
    statusField: "status",
    id: input.userId,
    transition: "reactivate",
    lifecycle: userLifecycle,
    errors: { notFound: UserNotFoundError, invalidTransition: InvalidStatusTransitionError },
  });
  if (!result.ok) return result;
  const user = await recomputeUserPermissions(db, input.userId);
  return ok({ user });
}
