<?php

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

use App\Classes\Modules\Currencies\Services\Rates\DeletesRate;
use App\Http\Resources\CurrencyRateResource;

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Currencies\Services\Rates\FetchesRate;

use App\Classes\Modules\Currencies\Standards\Rules\Rates\CanDeleteRate;

use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DeleteRateLogic extends AbstractControllerLogic
{

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

    /** @var CanDeleteRate */
    private $canDeleteRate;

    /** @var DeletesRate */
    private $deletesRate;

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


    /**
     * DeleteRateRateLogic constructor.
     * @param CanDeleteRate $canDeleteRate
     * @param DeletesRate $deletesRate
     * @param FetchesRate $fetchesRate
     */
    public function __construct(
        CanDeleteRate $canDeleteRate,
        DeletesRate $deletesRate,
        FetchesRate $fetchesRate
    )
    {
        $this->canDeleteRate = $canDeleteRate;
        $this->deletesRate = $deletesRate;
        $this->fetchesRate = $fetchesRate;
    }

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

            $currency_rate = $this->fetchesRate->execute(['id' => $request->route('id')]);
            $this->canDeleteRate->passes();
            $this->deletesRate->execute($currency_rate);
            
            DB::commit();

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

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

}