<?php

namespace App\Services;

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

class ImaginStudioApi
{
    /**
     * @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 [];
        }

        $response = Http::get($this->endpoint($colour_codes, $make_name));

        if ($response->successful()) {
            return $response->json();
        }

        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 [];
    }

    /**
     * @param string $colour_code
     * @param string $make_name
     * @return string
     */
    private function endpoint(Collection $colour_codes, string $make_name): string
    {
        $query = http_build_query([
            'customer' => Settings::get('imagin-placeholders-client-key', ''),
            'make' => strtolower($make_name),
            'paints' => $colour_codes->implode(','),
        ]);

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