<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class VehicleDetailsResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $this->resource->load([
            'primaryMediaUse.media',
            'make',
            'model',
            'fuelType',
            'transmission',
            'bodyStyle',
        ]);
        $resource = parent::toArray($request);
        $resource['preview_image'] = $this->previewImage();
        $resource['has_real_image'] = (bool) $this->resource->primaryMediaUse;

        return $resource;
    }

    protected function previewImage(): ?string
    {
        if ($this->resource->primaryMediaUse) {
            return $this->resource->primaryMediaUse->media->square_thumb_url
                ?? $this->resource->primaryMediaUse->media->original_url
                ?? null;
        }

        $key = Settings::get('imagin-placeholders-client-key')
            ?: config('services.imagin-studio.key');
        if (!$key) {
            return null;
        }

        return 'https://cdn.imagin.studio/getImage?' . http_build_query([
            'customer' => $key,
            'make' => $this->resource->make?->name,
            'modelFamily' => $this->resource->model?->name,
            'paintdescription' => $this->resource->colour,
            'modelYear' => $this->resource->manufacture_year,
            'aspectRatio' => '16:9',
            'zoomLevel' => 50,
        ]);
    }
}
