<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;

class UserManagementController extends Controller
{
    /**
     * Get list of users with pagination and search
     */
    public function index(Request $request): JsonResponse
    {
        // 1. Add withCount('posts') to get the post count efficiently
        $query = User::withCount('posts');

        // 2. Search logic (Added username search)
        if ($search = $request->input('search')) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('username', 'like', "%{$search}%");
            });
        }

        // Pagination
        $users = $query->orderBy('created_at', 'desc')->paginate(10);

        return response()->json($users);
    }

    /**
     * Update user details (Name, Email, Role)
     */
    public function update(Request $request, User $user): JsonResponse
    {
        // Prevent demo/admin lockout if needed (Optional safety)
        if ($user->id === auth()->id() && $request->role !== 'admin') {
            return response()->json(['message' => 'You cannot demote yourself.'], 403);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => ['required', 'email', Rule::unique('users')->ignore($user->id)],
            'role' => 'required|in:admin,user,editor', // Valid roles
        ]);

        $user->update($validated);

        return response()->json([
            'message' => 'User updated successfully.',
            'user' => $user
        ]);
    }

    /**
     * Delete a user
     */
    public function destroy(User $user): JsonResponse
    {
        // Prevent deleting self
        if ($user->id === auth()->id()) {
            return response()->json(['message' => 'You cannot delete yourself.'], 403);
        }

        // Optional: Delete associated content or let DB cascade handle it
        $user->delete();

        return response()->json(['message' => 'User deleted successfully.']);
    }
}