<?php

namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Mtc\AutoTraderStock\Services\AutoTraderApi as AutoTraderApiParent;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAutoTraderData;

class AutoTrader
{
    public function __construct(private readonly AutoTraderApi $api)
    {
    }

    public function getStock(int $advertiserId)
    {
        $pageSize = 200;
        $query = http_build_query([
            'advertiserId' => $advertiserId,
            'pageSize' => $pageSize,
            'responseMetrics' => true,
            'vehicleMetrics' => true,
        ]);
        $data = $this->api->get('stock?' . $query);
        if (!isset($data['totalResults'])) {
            // Bad data
            return [];
        }
        if ($data['totalResults'] > $pageSize) {
            $page = 1;
            do {
                $query = http_build_query([
                    'advertiserId' => $advertiserId,
                    'pageSize' => $pageSize,
                    'page' => ++$page,
                ]);
                $nextPage = $this->api->get('stock?' . $query);
                $data['results'] = array_merge($nextPage['results'], $data['results']);
            } while ($page * $pageSize < $data['totalResults']);
        }

        return $data['results'];
    }

    public function getAutoTraderData(int $advertiserId): void
    {
        collect($this->getStock($advertiserId))
            ->map(fn ($result) => [
                'uuid' => $result['metadata']['externalStockId'],
                'stockId' => $result['metadata']['stockId'] ?? null,
                'valuation' => $result['vehicle']['valuations']['marketAverage']['retail']['amountGBP'] ?? null,
                'price_point' => $result['adverts']['retailAdverts']['priceIndicatorRating'] ?? null,
                'price_position' => $result['vehicle']['vehicleMetrics']['local']['retail']['rating']['value'] ?? null,
                'search_results_7d' => $result['responseMetrics']['lastWeek']['searchViews'] ?? null,
                'ad_views' => $result['responseMetrics']['lastWeek']['advertViews'] ?? null,
            ])
            ->chunk(50)
            ->each(function ($atData) {

                $vehicles = Vehicle::query()->whereIn('uuid', $atData->pluck('uuid'))->pluck('id', 'uuid');
                if ($vehicles->isEmpty()) {
                    $vehicles = Vehicle::query()->whereIn('uuid', $atData->pluck('stockId'))->pluck('id', 'uuid');
                }
                $data = $atData->map(function ($data) use ($vehicles) {
                    $data['vehicle_id'] = $vehicles[$data['uuid']] ?? $vehicles[$data['stockId']] ?? null;
                    unset($data['uuid']);
                    unset($data['stockId']);
                    return $data;
                })
                    ->filter(fn($vehicleData) => $vehicleData['vehicle_id'])
                    ->toArray();

                VehicleAutoTraderData::query()->upsert($data, ['vehicle_id']);
            });
    }
}
