<?php

namespace App\Services;

use App\Facades\Settings;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ImaginStudioApi
{
    protected const ENDPOINT_GET_PAINT_SWATCHES = '/getPaintSwatches';
    protected const ENDPOINT_GET_VEHICLE_IMAGE = '/getImage';

    /**
     * @param string $colour_code
     * @param string $make_name
     * @return array
     */
    public function getColourData(Collection $colour_codes, string $make_name): array
    {
        if (Settings::get('imagin-placeholders-import-colour-enabled') == false) {
            return [];
        }

        $make_name = strtolower($make_name);

        $response = Http::get($this->endpoint(self::ENDPOINT_GET_PAINT_SWATCHES, [
            'make' => $make_name,
            'paints' => $colour_codes->implode(','),
        ]));

        if ($response->successful()) {
            $data = $response->json();

            if (is_array($data)) {
                return $data;
            }
        }

        Log::warning('Imagin Studio Colour import issue', [
            'tenant' => tenant('id'),
            'make_name' => $make_name,
            'colour_codes' => $colour_codes->implode(','),
            'response_code' => $response->status(),
            'response' => $response->body(),
        ]);

        return [];
    }

    public function getVehicleImage(
        string $make_name,
        string $model_name,
        string $paint_id,
        string $paint_description,
    ): void {
        if (
            Settings::get('imagin-placeholders-import-colour-enabled') == false
            || empty($make_name)
            || empty($model_name)
        ) {
            return;
        }

        Http::get($this->endpoint(self::ENDPOINT_GET_VEHICLE_IMAGE, [
            'make' => strtolower($make_name),
            'modelFamily' => strtolower($model_name),
            'paintId' => $paint_id,
            'paintDescription' => $paint_description,
        ]));
    }

    /**
     * @param string $colour_code
     * @param string $make_name
     * @return string
     */
    private function endpoint(string $enpoint, array $parameters): string
    {
        $query = http_build_query(
            array_merge(
                [
                    'customer' => Settings::get('imagin-placeholders-client-key', ''),
                ],
                $parameters
            )
        );

        return 'https://cdn.imagin.studio' . $enpoint . '?' . $query;
    }
}
