<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Support\FileUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class FeedingLogResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'project_id' => $this->project_id,
            'report_id' => $this->report_id,
            'feeding_meal_id' => $this->feeding_meal_id,
            'fed_at_date' => $this->fed_at_date?->toDateString(),
            'meal_time' => $this->meal_time,
            'meal_name' => $this->meal_name,
            'photos' => $this->formatFiles($this->photos),
            'photos_count' => is_array($this->photos) ? count($this->photos) : 0,
            'notes' => $this->notes,
            'created_at' => $this->created_at?->toISOString(),
            'creator' => new UserResource($this->whenLoaded('createdBy')),
            'feeding_meal' => $this->whenLoaded('feedingMeal', fn () => [
                'id' => $this->feedingMeal?->id,
                'meal_time' => $this->feedingMeal?->meal_time,
                'name' => $this->feedingMeal?->name,
                'percent_of_total' => $this->feedingMeal?->percent_of_total !== null
                    ? (float) $this->feedingMeal->percent_of_total
                    : null,
            ]),
        ];
    }

    private function formatFiles(?array $files): ?array
    {
        if ($files === null) {
            return null;
        }

        return array_map(
            fn ($file) => is_string($file) ? FileUrl::url($file) : null,
            $files
        );
    }
}
