<?php

namespace App\Classes\Modules\Currencies\ControllersLogic\Rates;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Currencies\Services\Rates\FetchesRate;
use App\Classes\Modules\Currencies\Services\Rates\CalculatesRate;

use App\Http\Resources\CalculateCurrencyRateResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CalculateRateLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Calculated Currency Rate',
            'message' => 'You have successfully rate calculated a Currency'
        ];
    }

    /** @var FetchesRate */
    private $fetchesRate;

    /** @var CalculatesRate */
    private $calculatesRate;

    /**
     * @param FetchesRate $fetchesRate
     * @param CalculatesRate $calculatesRate
     */
    public function __construct(FetchesRate $fetchesRate, CalculatesRate $calculatesRate)
    {
        $this->fetchesRate = $fetchesRate;
        $this->calculatesRate = $calculatesRate;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {
            $amount = $request->input('amount');
            $conversion_currency_rate = $this->fetchesRate->execute(
                [
                    'id' => $request->input('conversion_currency_rate_id'),
                ]
            );
            $convertable_currency_rate = $this->fetchesRate->execute(
                [
                    'id' => $request->input('convertable_currency_rate_id')
                ]
            );

            $convert_amount = $this->calculatesRate->execute($conversion_currency_rate, $convertable_currency_rate, $amount);

            return $this->resourceResponse(new CalculateCurrencyRateResource($conversion_currency_rate, $convertable_currency_rate, $convert_amount));

        } catch (\Exception $exception){
            throw new ErrorException($exception->getMessage(), $exception->getCode());
        }

    }

}