<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id'            => $this->id,
            'content'       => $this->content,
            'image_url'     => $this->image_path ? asset('storage/' . $this->image_path) : null,
            'visibility'    => $this->visibility,
            'created_at'    => $this->created_at->toISOString(),
            'user'          => new UserResource($this->whenLoaded('user')),
            'like_count'    => $this->likes_count ?? $this->likes()->count(),
            'liked_by_me'   => $this->whenLoaded('likes', fn() =>
                $this->likes->contains('user_id', $request->user()?->id)
            ),
            'likers'        => UserResource::collection($this->whenLoaded('likes',
                fn() => $this->likes->take(5)->map(fn($l) => $l->user)->filter()
            )),
            'comment_count' => $this->comments_count ?? $this->comments()->count(),
        ];
    }
}
