<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\RolePermissionService;
use Illuminate\Http\Request;

class UserManagementController extends Controller
{
    public function __construct(private readonly RolePermissionService $rolePermissionService)
    {
    }

    /**
     * Get all users (admin only)
     */
    public function index(Request $request)
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['view_users', 'manage_users'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $users = User::select('id', 'name', 'email', 'role', 'created_at', 'updated_at')
            ->orderBy('created_at', 'desc')
            ->get();

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

    /**
     * Update user role (admin only)
     */
    public function updateRole(Request $request, $id)
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['edit_users', 'assign_roles', 'manage_users'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $request->validate([
            'role' => 'required|string'
        ]);

        $user = User::findOrFail($id);
        $user->role = $request->role;
        $user->save();

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

    /**
     * Get all available roles
     */
    public function getRoles()
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['view_users', 'assign_roles', 'manage_users'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        return response()->json([
            'roles' => $this->rolePermissionService->listRoleIds()
        ]);
    }

    /**
     * Create a new custom role
     */
    public function createRole(Request $request)
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['manage_users', 'manage_role_permissions'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $request->validate([
            'role' => 'required|string|max:100'
        ]);

        try {
            $role = $this->rolePermissionService->createRole($request->role);
        } catch (\RuntimeException $exception) {
            return response()->json(['message' => $exception->getMessage()], 400);
        }

        return response()->json([
            'message' => 'Role created successfully',
            'role' => $role['id']
        ], 201);
    }

    /**
     * Update (rename) a role's display name and description
     */
    public function updateRoleMeta(Request $request, $roleId)
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['manage_users', 'manage_role_permissions'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
        ]);

        try {
            $role = $this->rolePermissionService->updateRoleMeta($roleId, $request->name, $request->description);
        } catch (\RuntimeException $exception) {
            return response()->json(['message' => $exception->getMessage()], 404);
        }

        return response()->json([
            'message' => 'Role updated successfully',
            'role' => ['id' => $role['id'], 'name' => $role['name']],
        ]);
    }

    /**
     * Delete a custom role
     */
    public function deleteRole(Request $request, $roleId)
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['manage_users', 'manage_role_permissions'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        try {
            $this->rolePermissionService->deleteRole($roleId);
        } catch (\RuntimeException $exception) {
            return response()->json(['message' => $exception->getMessage()], 400);
        }

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

    /**
     * Delete user (admin only)
     */
    public function destroy($id)
    {
        $currentUser = auth('api')->user();
        if (!$this->hasAnyPermission($currentUser->role, ['delete_users', 'manage_users'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $user = User::findOrFail($id);
        
        // Prevent deleting yourself
        if ($user->id === auth('api')->user()->id) {
            return response()->json(['message' => 'Cannot delete your own account'], 400);
        }

        $user->delete();

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

    private function hasAnyPermission(string $roleId, array $requiredPermissions): bool
    {
        return $this->rolePermissionService->hasAnyPermission($roleId, $requiredPermissions);
    }

    private function getRolePermissions(string $roleId): array
    {
        return $this->rolePermissionService->getPermissions($roleId);
    }
}
