<?php

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

use App\Classes\General\Abstracts\AbstractControllerLogic;

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

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

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


use App\Classes\Modules\Currencies\DataTransferObjects\RateObject;
use App\Http\Resources\CurrencyRateResource;

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

class UpdateRateLogic extends AbstractControllerLogic
{

    /** @var CanUpdateRate */
    private $canUpdateRate;
    /** @var UpdatesRate */
    private $updatesRate;
    /** @var CreatesRateLog */
    private $createsRateLog;
    /** @var FetchesRate */
    private $fetchesRate;

    /**
     * UpdateStandardRateLogic constructor.
     * @param CanUpdateRate $canUpdateRate
     * @param UpdatesRate $updatesRate
     * @param CreatesRateLog $createsRateLog
     * @param FetchesRate $fetchesRate
     */
    public function __construct(
        CanUpdateRate $canUpdateRate,
        UpdatesRate $updatesRate,
        CreatesRateLog $createsRateLog,
        FetchesRate $fetchesRate
    )
    {
        $this->canUpdateRate = $canUpdateRate;
        $this->updatesRate = $updatesRate;
        $this->createsRateLog = $createsRateLog;
        $this->fetchesRate = $fetchesRate;
    }

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

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

            $currency_object_object = new RateObject(
                $currency_rate_query->currency_id,
                 $request->input('selling', $currency_rate_query->selling),
                $currency_rate_query->payment_method_type
            );

            $this->canUpdateRate->passes($currency_object_object);
            $currency_rate_query = $this->updatesRate->execute($currency_rate_query, $currency_object_object);

            $this->createsRateLog->execute($currency_rate_query);

            DB::commit();

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

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

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

}