<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\AssetResource;
use App\Models\Asset;
use Illuminate\Http\Request;
class AssetApiController extends Controller
{
    private function guard(Request $r): void { abort_unless($r->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']),403); }
    public function index(Request $request) {
        $this->guard($request);
        $assets = Asset::with(['category','model.manufacturer','assignedUser','department'])
            ->when($request->category,fn($q)=>$q->where('category_id',$request->category))
            ->when($request->status,  fn($q)=>$q->where('status',$request->status))
            ->when($request->q, fn($q)=>$q->where(fn($s)=>$s->where('name','like','%'.$request->q.'%')->orWhere('code','like','%'.$request->q.'%')->orWhere('serial_number','like','%'.$request->q.'%')))
            ->orderBy('code')->paginate(min((int)($request->per_page??20),100));
        return AssetResource::collection($assets)->additional(['success'=>true]);
    }
    public function show(Request $request, Asset $asset) {
        $this->guard($request);
        $asset->load(['category','model.manufacturer','assignedUser','department']);
        return response()->json(['success'=>true,'data'=>new AssetResource($asset)]);
    }
    public function byCode(Request $request, string $code) {
        $this->guard($request);
        $asset = Asset::where('code',$code)->with(['category','assignedUser','department'])->firstOrFail();
        return response()->json(['success'=>true,'data'=>new AssetResource($asset)]);
    }
}
