<?php

namespace App\Http\Resources;

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

/** @mixin MealPosts */
class MealPostsResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $user = $this->user;

        return [
            'id' => $this->id,
            'imageUrl' => $this->imageUrl(),
            'caption' => $this->caption,
            'calories' => $this->calories,
            'proteins' => $this->proteins,
            'carbs' => $this->carbs,
            'fats' => $this->fats,
            'title' => $this->title,
            'visibility' => $this->visibility,
            'type' => $this->type,
            'aiGenerated' => $this->ai_generated,
            'dietType' => $this->diet_type,
            'likesCount' => (int) ($this->liked_by_users_count ?? 0),
            'likedByMe' => (bool) ($this->liked_by_current_user ?? false),
            'eatenAt' => $this->eaten_at,
            'createdAt' => $this->created_at,
            'updatedAt' => $this->updated_at,
            'ingredients' => MealPostIngredientsResource::collection($this->whenLoaded('ingredients')),

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

    private function imageUrl(): ?string
    {
        if (! $this->image_url) {
            return null;
        }

        if (Str::startsWith($this->image_url, ['http://', 'https://'])) {
            return $this->image_url;
        }

        return asset(Storage::url($this->image_url));
    }
}
