<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    public function getRoles(Request $request): JsonResponse
    {
        $roles = Role::with('permissions')->get();

        return response()->json([
            'data' => $roles,
        ], JsonResponse::HTTP_OK);
    }

    public function getPermissions(Request $request): JsonResponse
    {
        $permissions = Permission::query()->orderBy('name')->get()->sortBy(function (Permission $permission) {
            if (str_starts_with($permission->name, 'ranch.')) {
                return '0_'.$permission->name;
            }
            if (str_starts_with($permission->name, 'administracion.')) {
                return '1_'.$permission->name;
            }
            if ($permission->name === 'dashboard.ver') {
                return '2_'.$permission->name;
            }

            return '9_'.$permission->name;
        })->values();

        return response()->json([
            'data' => $permissions,
        ], JsonResponse::HTTP_OK);
    }

    public function updateRolePermissions(Request $request, Role $role): JsonResponse
    {
        $request->validate([
            'permissions' => 'required|array',
            'permissions.*' => 'exists:permissions,name',
        ]);

        $role->syncPermissions($request->permissions);

        return response()->json([
            'message' => 'Permisos actualizados correctamente',
            'data' => $role->load('permissions'),
        ], JsonResponse::HTTP_OK);
    }
}
