<?php

namespace App\Classes\Modules\Companies\ControllersLogic;


use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\RequestValidationException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Bookings\Services\FetchesBookingQuotation;
use App\Classes\Modules\Bookings\Services\GeneratesBookingQuotation;
use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject;
use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Models\Company;
use App\Models\Currency;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FetchCompanyBookingQuotationLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Fetch Currency Conversion',
            'message' => 'You have successfully retrieved a currency conversion'
        ];
    }


    /** @var FetchesBookingQuotation */
    private $fetchBookingQuotation;

    /** @var GeneratesBookingQuotation */
    private $generatesBookingQuotation;

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

    /**
     * FetchCompanyBookingQuotationLogic constructor.
     * @param FetchesBookingQuotation $fetchBookingQuotation
     * @param GeneratesBookingQuotation $generatesBookingQuotation
     * @param FetchesCurrency $fetchesCurrency
     */
    public function __construct(FetchesBookingQuotation $fetchBookingQuotation, GeneratesBookingQuotation $generatesBookingQuotation, FetchesCurrency $fetchesCurrency)
    {
        $this->fetchBookingQuotation = $fetchBookingQuotation;
        $this->generatesBookingQuotation = $generatesBookingQuotation;
        $this->fetchesCurrency = $fetchesCurrency;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws MalformedRequestException
     * @throws RequestValidationException
     */
    public function logic(Request $request) : JsonResponse
    {
        /** @var Company $company */
        $company = Company::find($request->route('id'));

        $conversionObject = new CurrencyConversionObject(floatval(str_replace(',', '', $request->input('amount'))), $request->input('currency_id'), $request->input('service_id'), $request->input('type'));

        $calculationObject = $this->fetchBookingQuotation->execute($company, $conversionObject);

        /** @var Currency $currency */
        $currency = $this->fetchesCurrency->execute(['id' => $conversionObject->getCurrencyId()]);
        if($calculationObject->getConvertibleTotal() < $calculationObject->getConfigurations()->getMinLimit()) throw new RequestValidationException('Your transfer is below the minimum amount allowed of '.$calculationObject->getConfigurations()->getMinLimit().' '.$currency->short_code);

        //TODO  add po limit validation
        return $this->response(['data' => $this->generatesBookingQuotation->execute($calculationObject)]);

    }


}