"use server";

import "server-only";
import { getSession } from "@/lib/auth";
import { setUserPassword } from "@/lib/auth";
import { getAdminUser } from "@/lib/admin-permissions";

const MIN_PASSWORD_LENGTH = 8;

/**
 * Change a user's password. Requires admin privileges.
 * 
 * Use this for admin-initiated password resets. For self-service
 * password changes, users should use the forgot password flow.
 */
export async function updatePasswordAction(
  userId: string,
  newPassword: string
): Promise<{ success: boolean; error?: string }> {
  // Verify the caller is an admin
  const adminUser = await getAdminUser();
  if (!adminUser) {
    return { success: false, error: "Not authenticated. Please log in again." };
  }

  if (adminUser.role !== "platform_admin") {
    return { success: false, error: "Only platform admins can change passwords." };
  }

  // Validate password
  if (!newPassword || newPassword.length < MIN_PASSWORD_LENGTH) {
    return { success: false, error: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.` };
  }

  try {
    const result = await setUserPassword({
      userId,
      newPassword,
    });

    if (result.error) {
      console.error("[updatePassword] Failed:", result.error);
      return { success: false, error: result.error.message ?? "Failed to update password." };
    }

    console.log("[updatePassword] Password updated for user:", userId);
    return { success: true };
  } catch (err) {
    console.error("[updatePassword] Unexpected error:", err);
    return { success: false, error: "An unexpected error occurred." };
  }
}

/**
 * Get the current session user ID. Used by the change-password UI.
 */
export async function getCurrentUserId(): Promise<string | null> {
  const { data: session } = await getSession();
  return session?.user?.id ?? null;
}
