<?php

namespace App\Http\Resources;

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

class ReviewResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id'          => $this->id,
            'schedule_id' => $this->schedule_id,

            'schedule_label' => $this->schedule
                ? ($this->schedule->id.' - '.
                   ($this->schedule->client?->user?->name   ?? '?').' - '.
                   ($this->schedule->provider?->user?->name ?? '?').' - '.
                   ($this->schedule->date?->format('d/m/Y') ?? '?'))
                : null,

            'origin'    => $this->origin,
            'origin_id' => $this->origin_id,
            'stars'     => $this->stars,
            'comment'   => $this->comment,

            'reviews_improvements' => $this->whenLoaded('reviewsImprovements', function () {
                return $this->reviewsImprovements->map(function ($type) {
                    return [
                        'id'          => $type->improvementType->id,
                        'description' => $type->improvementType->description,
                    ];
                });
            }),

            'photos' => $this->whenLoaded('reviewMedia', function () {
                return $this->reviewMedia->map(fn ($rm) => [
                    'id'     => $rm->media_id,
                    'origin' => $rm->origin,
                    'url'    => $rm->media?->path
                        ? Storage::temporaryUrl($rm->media->path, now()->addMinutes(60))
                        : null,
                ]);
            }),

            'created_at' => $this->created_at?->format('Y-m-d H:i'),
            'updated_at' => $this->updated_at?->format('Y-m-d H:i'),
        ];
    }
}
