<?php

namespace Maestro\Core\Http\Controllers;

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

class RoleController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(Role::with('permissions')->get());
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name'        => 'required|string|unique:roles',
            'permissions' => 'nullable|array',
        ]);

        $permissions = $validated['permissions'] ?? [];
        unset($validated['permissions']);

        $role = Role::create(['name' => $validated['name'], 'guard_name' => 'web']);
        $role->syncPermissions($permissions);

        return response()->json($role->load('permissions'), 201);
    }

    public function update(Request $request, Role $role): JsonResponse
    {
        $validated = $request->validate([
            'name'        => 'sometimes|string|unique:roles,name,'.$role->id,
            'permissions' => 'sometimes|nullable|array',
        ]);

        $permissions = $validated['permissions'] ?? null;
        unset($validated['permissions']);

        $role->update($validated);

        if ($permissions !== null) {
            $role->syncPermissions($permissions);
        }

        return response()->json($role->load('permissions'));
    }

    public function destroy(Role $role): JsonResponse
    {
        $role->delete();
        return response()->json(['message' => 'Role deleted']);
    }

    public function permissions(): JsonResponse
    {
        return response()->json(Permission::all());
    }
}
