<?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\Standards\Rules\Rates\CanFetchRate;
use App\Http\Resources\CurrencyRateResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FetchRateLogic extends AbstractControllerLogic
{

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

    /** @var CanFetchRate */
    private $canFetchRate;

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

    /**
     * FetchRateControllersLogic constructor.
     * @param CanFetchRate $canFetchRate
     * @param FetchesRate $fetchesRate
     */
    public function __construct(CanFetchRate $canFetchRate, FetchesRate $fetchesRate)
    {
        $this->canFetchRate = $canFetchRate;
        $this->fetchesRate = $fetchesRate;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {

            $this->canFetchRate->passes();

            $query = $this->fetchesRate->execute(['id' => $request->route('id')]);

            return $this->resourceResponse(new CurrencyRateResource($query));

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

    }

}