<?php

namespace App\Services;

use App\Contracts\AddsDealershipFields;
use App\Facades\Settings;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\ApiNotification;

class Pyxel implements AddsDealershipFields
{
    public function getVehicleMedia(string $locationId): ?array
    {
        $params = array_filter([
            'PID' => $this->apiKey(),
            'VID' => Settings::get('image-sync-pyxel-version-id'),
            'AID' => $locationId
        ]);

        $response = Http::get($this->endpoint('AdvertData?' . http_build_query($params)));
        ApiNotification::query()
            ->create([
                'provider' => 'pyxel',
                'data' => $response->json(),
                'processed' => $response->successful(),
                'data_model' => 'dealership',
                'reference' => $locationId,

            ]);

        return $response->json();
    }

    /**
     * Get the endpoint on AutosOnShow
     *
     * @param string $path
     * @return string
     */
    private function endpoint(string $path): string
    {
        return 'https://server.imageconsole.com/api2/' . ltrim($path, '/');
    }

    public function dealershipAdditionalDataFields(): array
    {
        return [
            'pyxel-dealership' => [
                'type' => 'text',
                'label' => 'Name of dealership on Pxyel'
            ],
        ];
    }

    public function enabled(): bool
    {
        return Settings::get('image-sync-pyxel-enabled', false);
    }

    private function apiKey(): string
    {
        return match (Settings::get('app-details-country')) {
            'IE' => Config::get('services.pyxel.IE.client_id'),
            default => Config::get('services.pyxel.GB.client_id'),
        };
    }
}
