<?php

namespace App\Master\Services;

use App\Services\AutoTraderApi;

class AutoTraderTaxonomyService
{
    /**
     * Constructor
     *
     * @param AutoTraderApi $api
     */
    public function __construct(protected AutoTraderApi $api)
    {
        //
    }

    /**
     * Get list of makes available on AutoTrader
     *
     * @return array
     */
    public function getMakes(): array
    {
        $carParams = [
            'advertiserId' => config('services.auto-trader.merchant_id'),
            'vehicleType' => 'Car',
        ];
        $vanParams = [
            'advertiserId' => config('services.auto-trader.merchant_id'),
            'vehicleType' => 'Van',
        ];
        $cars = collect($this->api->get("taxonomy/makes?" . $this->params($carParams)))
            ->flatten(1)
            ->toArray();

        $vans = collect($this->api->get("taxonomy/makes?" . $this->params($vanParams)))
            ->flatten(1)
            ->toArray();
        return array_merge($cars, $vans);
    }

    /**
     * Get list of make models available on AutoTrader
     *
     * @return array
     */
    public function getModels(string $make_id): array
    {
        $params = [
            'advertiserId' => config('services.auto-trader.merchant_id'),
            'vehicleType' => 'Car',
            'makeId' => $make_id
        ];
        $cars = collect($this->api->get("taxonomy/models?" . $this->params($params)))
            ->flatten(1)
            ->toArray();
        $params = [
            'advertiserId' => config('services.auto-trader.merchant_id'),
            'vehicleType' => 'Van',
            'makeId' => $make_id
        ];
        $vans = collect($this->api->get("taxonomy/models?" . $this->params($params)))
            ->flatten(1)
            ->toArray();

        return array_merge($cars, $vans);
    }

    /**
     * Convert params to a query string
     *
     * @param array $params
     * @return string
     */
    private function params(array $params): string
    {
        return collect($params)
            ->map(function ($value, $key) {
                return $key . '=' . $value;
            })->implode('&');
    }
}
