<?php

namespace App;

use Mtc\MercuryDataModels\ValuationAdjustment;
use Mtc\MercuryDataModels\VehicleValuation;
use Illuminate\Database\Eloquent\Builder;
use Mtc\VehicleValuation\Contracts\HasFutureValuations;
use Mtc\VehicleValuation\Contracts\ValuationResponse;

class ValuationRepository extends \Mtc\VehicleValuation\ValuationRepository
{
    protected function getQuery(): Builder
    {
        return VehicleValuation::query();
    }

    /**
     * Store a valuation result from API
     *
     * @param ValuationResponse $valuation
     * @return Builder|Model
     */
    protected function store(ValuationResponse $valuation): VehicleValuation
    {
        return $this->adjustValuation(parent::store($valuation));
    }

    protected function adjustValuation($valuation)
    {
        $valuationAdjustments = ValuationAdjustment::query()
            ->with('rules')
            ->active()
            ->get();

        foreach ($valuationAdjustments as $valuationAdjustment) {
            if ($valuationAdjustment->evaluate($valuation)) {
                $valuation->adjust($valuationAdjustment);
                break;
            }
        }

        return $valuation;
    }

    public function hasFutureValuations(): bool
    {
        return $this->getApiDriver() instanceof HasFutureValuations;
    }

    public function getFutureValuation(VehicleValuation $valuation, int $mileage_per_year, string $condition): array
    {
        return $this->getApiDriver()->getFutureValuation($valuation, $mileage_per_year, $condition);
    }

    public function testProvider(string $registration, int $mileage, ?string $variant_id): ValuationResponse
    {
        return $this->getApiDriver()->getValuation($registration, $mileage, $variant_id);
    }
}
