<?php

namespace App;

use Mtc\MercuryDataModels\ValuationAdjustment;
use Mtc\MercuryDataModels\VehicleValuation;
use Illuminate\Database\Eloquent\Builder;
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;
    }
}
