<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
class UserApiController extends Controller
{
    public function index(Request $request) {
        abort_unless($request->user()->hasAnyRole(['admin','superadmin','jefe_soporte']),403);
        $users = User::with('department')
            ->when($request->role, fn($q)=>$q->role($request->role))
            ->when($request->q,    fn($q)=>$q->where(fn($s)=>$s->where('name','like','%'.$request->q.'%')->orWhere('email','like','%'.$request->q.'%')))
            ->orderBy('name')->paginate(min((int)($request->per_page??20),100));
        return UserResource::collection($users)->additional(['success'=>true]);
    }
    public function agents(Request $request) {
        abort_unless($request->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']),403);
        $agents = User::role(['agente','jefe_soporte','admin','superadmin'])->withCount(['assignedTickets'=>fn($q)=>$q->open()])->orderBy('name')->get();
        return response()->json(['success'=>true,'data'=>UserResource::collection($agents)]);
    }
}
