<?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|null
     */
    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(),
            fn() => Http::post($this->endpoint('token'), [
                'grant_type' => 'client_credentials',
                'client_id' => Settings::get('image-sync-autos-on-show-client_id'),
                'client_secret' => Settings::get('image-sync-autos-on-show-client_secret'),
            ])->json('access_token')
        );
    }

    /**
     * Get the endpoint on AutosOnShow
     *
     * @param string $path
     * @return string
     */
    private function endpoint(string $path): string
    {
        // UAT environment not working at development time.
        // Currently no client_id_test setting, so will always use live URL,
        // however this setting could be added if UAT environment should be used.
        return !empty(Settings::get('image-sync-autos-on-show-client_id_test'))
            ? 'https://uat-api.aos.tv/v2/' . ltrim($path, '/')
            : 'https://api.aos.tv/v2/' . ltrim($path, '/');
    }
}
