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

export interface ActivateUserInput {
  userId: string;
  from?: 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 user = await db
    .selectFrom("User")
    .selectAll()
    .where("id", "=", input.userId)
    .forUpdate()
    .executeTakeFirst();

  if (!user) {
    return err(new UserNotFoundError(input.userId));
  }

  const validFromStatuses = input.from ?? ["PENDING"];
  if (!validFromStatuses.includes(user.status)) {
    return err(new InvalidStatusTransitionError(`${user.status} to ACTIVE`));
  }

  const updatedUser = await db
    .updateTable("User")
    .set({
      status: "ACTIVE",
      updatedAt: new Date(),
    })
    .where("id", "=", input.userId)
    .returningAll()
    .executeTakeFirst();

  return ok({ user: updatedUser! });
}
