<?php

namespace App\Http\Resources;

use App\Models\PostReviews;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;

/** @mixin PostReviews */
class PostReviewsResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'rating' => $this->rating,
            'comment' => $this->comment,
            'meal_post_id' => $this->meal_post_id,
            'user_id' => $this->user_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'mealPost' => new MealPostsResource($this->whenLoaded('mealPost')),
            'user' => $this->whenLoaded('user', function (): ?array {
                if (! $this->user) {
                    return null;
                }

                return [
                    'id' => $this->user->id,
                    'name' => $this->user->name,
                    'avatarUrl' => $this->user->avatar_url ? asset(Storage::url($this->user->avatar_url)) : null,
                ];
            }),
        ];
    }
}
