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

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

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

  const validFromStatuses = input.from ?? ["INACTIVE"];
  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! });
}
