<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

class RoleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Role::query();
        
        if ($request->has('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }
        
        if ($request->has('active')) {
            $query->where('is_active', $request->boolean('active'));
        }
        
        $roles = $query->orderBy('name')->get();
        
        return response()->json($roles);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $validated['slug'] = Str::slug($request->name);
        
        $role = Role::create($validated);
        
        return response()->json($role, 201);
    }

    public function show(string $id): JsonResponse
    {
        $role = Role::with('users')->findOrFail($id);
        return response()->json($role);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        $role = Role::findOrFail($id);
        
        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        if (isset($validated['name'])) {
            $validated['slug'] = Str::slug($validated['name']);
        }
        
        $role->update($validated);
        
        return response()->json($role);
    }

    public function destroy(string $id): JsonResponse
    {
        $role = Role::findOrFail($id);
        
        if ($role->users()->count() > 0) {
            return response()->json(['error' => 'Cannot delete role with users'], 400);
        }
        
        $role->delete();
        
        return response()->json(['message' => 'Role deleted successfully']);
    }
}
