<?php

namespace App\Classes\Modules\Bookings\Services;


use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Modules\Bookings\DataTransferObjects\CalculationObject;
use App\Classes\Modules\Companies\Services\FetchesCompanyServiceSettings;
use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject;
use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Models\Company;
use App\Models\Currency;

class FetchesBookingQuotation
{

    /** @var FetchesCompanyServiceSettings */
    private $fetchesCompanyServiceSettings;

    /** @var FetchesCurrency */
    private $fetchesCurrency;

    /**
     * FetchesBookingQuotation constructor.
     * @param FetchesCompanyServiceSettings $fetchesCompanyServiceSettings
     * @param FetchesCurrency $fetchesCurrency
     */
    public function __construct(FetchesCompanyServiceSettings $fetchesCompanyServiceSettings, FetchesCurrency $fetchesCurrency)
    {
        $this->fetchesCompanyServiceSettings = $fetchesCompanyServiceSettings;
        $this->fetchesCurrency = $fetchesCurrency;
    }


    /**
     * @param Company $company
     * @param CurrencyConversionObject $conversionObject
     * @return CalculationObject
     * @throws MalformedRequestException
     */
    public function execute(Company $company, CurrencyConversionObject $conversionObject){
        if($conversionObject->getAmount() <= 0) throw new MalformedRequestException('Your transfer must be greater than zero.');

        $configurations = $this->fetchesCompanyServiceSettings->execute($company, $conversionObject);

        /** @var Currency $currency */
        $currency = $this->fetchesCurrency->execute(['id' => $conversionObject->getCurrencyId()]);
        if($conversionObject->getAmount() > $configurations->getMaxLimit()) throw new MalformedRequestException('Your transfer can\'t be greater than '.number_format( floatval(str_replace(',', '', $configurations->getMaxLimit())), 2, '.', ',').' '.$currency->short_code);

        $calculationObject = new CalculationObject($conversionObject, $configurations);

        return $calculationObject;
    }

}