'use server';

// src/app/settings/actions.ts

import { auth } from "@/auth";
import { revalidatePath } from "next/cache";
import { getUserByEmail, getUserById, updateUserRole } from "@/data-access/users";

/**
 * Toggles a user's role between 'ADMIN' and 'USER' using the DAL pattern.
 */
export async function toggleUserRoleAction(targetUserId: string) {
  const session = await auth();
  const callerEmail = session?.user?.email;

  if (!callerEmail) {
    throw new Error("Unauthorized: No session found.");
  }

  // 1. Authorization: Verify caller's permissions via DAL
  const isBootstrap = callerEmail === process.env.INITIAL_ADMIN_EMAIL;
  const callerDbRecord = await getUserByEmail(callerEmail);
  const isAdmin = isBootstrap || callerDbRecord?.role === "ADMIN";

  if (!isAdmin) {
    throw new Error("Forbidden: You do not have permission to manage roles.");
  }

  // 2. Fetch target user via DAL
  const targetUser = await getUserById(targetUserId);

  if (!targetUser) {
    throw new Error("User not found.");
  }

  // 3. Protection: Prevent demoting the primary bootstrap admin
  if (targetUser.email === process.env.INITIAL_ADMIN_EMAIL && targetUser.role === "ADMIN") {
    throw new Error("Security Restriction: The primary Bootstrap Admin role cannot be removed.");
  }

  // 4. Logic: Determine new role
  const newRole = targetUser.role === "ADMIN" ? "USER" : "ADMIN";

  // 5. Execute Update via DAL
  await updateUserRole(targetUserId, newRole);

  // 6. UI Invalidation
  revalidatePath("/settings");

  return { 
    success: true, 
    message: `User ${targetUser.email} is now a ${newRole}` 
  };
}