"use server";

import * as authAdmin from "@/lib/auth-admin";

export type ResetAdminPasswordResult =
  | { success: true; tempPassword: string }
  | { success: false; error: string };

/**
 * Emergency recovery action — only usable in development or when the caller
 * already has service role access. Resets the password for the specified email
 * and returns the temp password so it can be displayed to the user.
 */
export async function resetAdminPassword(
  email: string,
  newPassword: string
): Promise<ResetAdminPasswordResult> {
  // Look up auth user by email
  const { data: users, error: listError } = await authAdmin.listUsers({ searchValue: email });
  if (listError) {
    return { success: false, error: "Could not list users: " + listError.message };
  }

  const authUser = (users ?? []).find((u) => u.email?.toLowerCase() === email.toLowerCase());
  if (!authUser) {
    return { success: false, error: "No auth user found for that email address." };
  }

  // Update password via the better-auth admin wrapper (uses `update_user_password` RPC internally)
  const { error: updateError } = await authAdmin.setUserPassword(authUser.id, newPassword);

  if (updateError) {
    return { success: false, error: updateError.message };
  }

  return { success: true, tempPassword: newPassword };
}