<?php

namespace App\Services;

use App\Facades\Settings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class AutosOnShow
{
    /**
     * Get media data for a specific vehicle
     *
     * @param string $vehicleId
     * @return array
     */
    public function getVehicleMedia(string $vehicleId): array
    {
        return Http::withHeaders(['Authorization' => 'Bearer ' . $this->authToken()])
            ->get($this->endpoint('vehicles/' . str_replace(' ', '', $vehicleId)))
            ->json();
    }

    /**
     * Get auth token
     *
     * @return mixed
     */
    private function authToken()
    {
        return Cache::remember(
            'autos-on-show-auth-token-' . tenant('id'),
            now()->addHour(),
            function () {
                return Http::post($this->endpoint('token'), [
                    'form_params' => [
                        'grant_type' => 'client_credentials',
                        'client_id' => Settings::get('image-sync-auto-imaging-client_id'),
                        'client_secret' => Settings::get('image-sync-auto-imaging-client_secret'),
                    ]
                ])->json('access_token');
            }
        );
    }

    /**
     * Get the endpoint on AutosOnShow
     *
     * @param string $path
     * @return string
     */
    private function endpoint(string $path): string
    {
        return config('services.image-sync-auto-imaging-live_api')
            ? 'https://api.autosonshow.tv/v2/' . ltrim($path, '/')
            : 'https://uat-api.aos.tv/v2/' . ltrim($path, '/');
    }
}
