<?php

namespace App\Services;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class AutoTraderAIApi extends AutoTraderApi
{
    #[\Override]
    protected function cacheName(string $key): string
    {
        return 'auto-trader-ai-api' . $key;
    }

    public function patchVehicle(string $stockId, array $payload, ?string $advertiserId = null): Response
    {
        $params = [
            'advertiserId' => $advertiserId,
        ];
        $url = "stock/" . $stockId . '?' . http_build_query($params);
        return $this->patch($url, $payload);
    }

    public function deleteVehicle(string $stockId, string $advertiserId): Response
    {
        return $this->patchVehicle(
            $stockId,
            [
                'metadata' => [
                    'lifecycleState' => 'DELETED',
                ],
                'adverts' => [
                    'retailAdverts' => [
                        'advertiserAdvert' => ['status' => 'NOT_PUBLISHED'],
                        'autotraderAdvert' => ['status' => 'NOT_PUBLISHED'],
                        'profileAdvert' => ['status' => 'NOT_PUBLISHED'],
                        'locatorAdvert' => ['status' => 'NOT_PUBLISHED'],
                        'exportAdvert' => ['status' => 'NOT_PUBLISHED'],
                    ],
                ],
            ],
            $advertiserId,
        );
    }

    public function patch(string $path, $data): Response
    {
        return Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->accessToken()
        ])->patch($this->endpoint($path), $data);
    }
}
