<?php

namespace App\Services;

use Illuminate\Http\Client\Response;

/**
 * Write/lookup operations against the AutoTrader Stock API.
 *
 * Ported from the standalone autotrader-microservice (App\Services\AutoTraderService) so the
 * vehicle send/remove workflow can run in-process. Delegates HTTP to App\Services\AutoTraderApi,
 * which handles OAuth token caching and sandbox/live endpoint resolution.
 */
class AutoTraderStockWriter
{
    public function __construct(
        private readonly ?string $advertiserId,
        private readonly AutoTraderApi $api,
    ) {
    }

    public function postVehicle(array $payload, ?string $alternateAdvertiserId = null): Response
    {
        $url = 'stock?' . $this->buildParams([
            'advertiserId' => $alternateAdvertiserId ?: $this->advertiserId,
        ]);

        return $this->api->postForResponse($url, $payload);
    }

    public function patchVehicle(string $stockId, array $payload, ?string $alternateAdvertiserId = null): Response
    {
        $url = 'stock/' . $stockId . '?' . $this->buildParams([
            'advertiserId' => $alternateAdvertiserId ?: $this->advertiserId,
        ]);

        return $this->api->patch($url, $payload);
    }

    public function uploadImage($contents, string $fileName, ?string $alternateAdvertiserId = null): Response
    {
        $url = 'images?' . $this->buildParams([
            'advertiserId' => $alternateAdvertiserId ?: $this->advertiserId,
        ]);

        return $this->api->postFile($url, $contents, $fileName);
    }

    public function findVehicleDetails(
        string $identifier,
        ?string $alternateAdvertiserId = null,
        string $type = 'registration'
    ): ?array {
        try {
            $url = 'vehicles?' . $this->buildParams([
                $type => str_replace(' ', '', $identifier),
                'advertiserId' => $alternateAdvertiserId ?: $this->advertiserId,
            ]);

            return $this->api->get($url, 'vehicle');
        } catch (\Exception) {
            return [];
        }
    }

    public function findVehicleByDerivative(string $derivativeId, ?string $alternateAdvertiserId = null): ?array
    {
        try {
            $url = 'taxonomy/derivatives/' . $derivativeId . '?' . $this->buildParams([
                'advertiserId' => $alternateAdvertiserId ?: $this->advertiserId,
            ]);

            return $this->api->get($url);
        } catch (\Exception) {
            return [];
        }
    }

    public function findStockId(string $stockId, ?string $alternateAdvertiserId = null): ?array
    {
        try {
            $url = 'stock?' . $this->buildParams([
                'stockId' => $stockId,
                'advertiserId' => $alternateAdvertiserId ?: $this->advertiserId,
            ]);

            return $this->api->get($url, 'results.0');
        } catch (\Exception) {
            return [];
        }
    }

    private function buildParams(array $params): string
    {
        return collect($params)
            ->map(fn ($value, $key) => $key . '=' . $value)
            ->implode('&');
    }
}
