<?php
namespace App\Http\Resources\Api;
use Illuminate\Http\Resources\Json\JsonResource;
class TicketDetailResource extends JsonResource
{
    public function toArray($request): array {
        $base    = (new TicketResource($this))->toArray($request);
        $isAgent = $request->user()?->hasAnyRole(['agente','admin','superadmin','jefe_soporte']);
        return array_merge($base, [
            'comments' => $this->whenLoaded('comments', fn() =>
                $this->comments->filter(fn($c) => !$c->is_internal || $isAgent)
                    ->map(fn($c) => ['id'=>$c->id,'body'=>$c->body,'is_internal'=>$c->is_internal,
                        'user'=>$c->user?['id'=>$c->user->id,'name'=>$c->user->name]:null,
                        'created_at'=>$c->created_at->toIso8601String()])->values()
            ),
            'history' => $this->whenLoaded('history', fn() =>
                $this->history->map(fn($h) => ['id'=>$h->id,'action'=>$h->action,'description'=>$h->description,
                    'user'=>$h->user?['id'=>$h->user->id,'name'=>$h->user->name]:null,
                    'created_at'=>$h->created_at->toIso8601String()])
            ),
            'asset' => $this->asset ? ['id'=>$this->asset->id,'code'=>$this->asset->code,'name'=>$this->asset->name] : null,
        ]);
    }
}
