<?php

namespace App\Http\Resources\Traits;

use App\Facades\Settings;
use Mtc\MercuryDataModels\Vehicle;

trait FormatsAutoTraderData
{
    protected function getAutoTraderData(Vehicle $vehicle): ?array
    {
        if (!Settings::get('autotrader-advert-performance')) {
            return null;
        }

        $data = [
            'price_point' => $vehicle->autoTraderData?->price_point,
        ];

        if (Settings::get('autotrader-show-valuation-saving')) {
            $data['valuation_saving'] = $this->resolveValuationSaving($vehicle);
        }

        return $data;
    }

    private function resolveValuationSaving(Vehicle $vehicle): ?int
    {
        $valuation = $vehicle->autoTraderData?->valuation;

        if (!$valuation || !$vehicle->price) {
            return null;
        }

        $saving = $valuation - $vehicle->price;
        $threshold = (int) Settings::get('autotrader-valuation-saving-threshold', 0);

        return $saving >= $threshold ? $saving : null;
    }
}
