<?php

namespace App\Services;

use App\Contracts\AIContentDriver;
use App\Facades\Settings;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAutoTraderData;
use Mtc\MercuryDataModels\VehicleOffer;

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

    public function canGenerateDescriptionOnImport(): bool
    {
        return (bool)Settings::get('ai-content-auto-trader-generate-description-on-vehicle-import');
    }

    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']);
            });
    }

    public function getDescription(Vehicle|VehicleOffer $model): string
    {
        if (empty($model->auto_trader_id)) {
            return '';
        }

        $response = $this->api->post(
            "co-driver/stock/{$model->auto_trader_id}",
            [],
            [
                'query' => [
                    'description' => 'true',
                    'advertiserId' => $this->getVehicleAdvertiserId($model),
                ]
            ]
        );

        return $response['adverts']['retailAdverts']['description'] ?? '';
    }

    protected function getVehicleAdvertiserId(Vehicle|VehicleOffer $model): int
    {
        if (!empty($model->dealership->data['autotrader-dealer-id'])) {
            return $model->dealership->data['autotrader-dealer-id'];
        }

        return Settings::get('auto-trader-advertiser-id');
    }
}
