<?php

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

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Currencies\Services\FetchesCurrency;

use App\Classes\Modules\Currencies\Services\Rates\CreatesRateLog;
use App\Classes\Modules\Currencies\Standards\Rules\Rates\CanCreateRate;
use App\Classes\Modules\Currencies\Services\Rates\CreatesRate;
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 CreateRateLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Created Currency Rate',
            'message' => 'You have successfully created a new Currency Rate'
        ];
    }

    /** @var CanCreateRate */
    private $canCreateRate;

    /** @var CreatesRate */
    private $createsRate;

    /** @var CreatesRateLog */
    private $createsRateLog;

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

    /**
     * CreateRateLogic constructor.
     * @param CanCreateRate $canCreateRate
     * @param CreatesRate $createsRate
     * @param CreatesRateLog $createsRateLog
     * @param FetchesCurrency $fetchesCurrency
     */
    public function __construct(
        CanCreateRate $canCreateRate,
        CreatesRate $createsRate,
        CreatesRateLog $createsRateLog,
        FetchesCurrency $fetchesCurrency
    )
    {
        $this->canCreateRate = $canCreateRate;
        $this->createsRate = $createsRate;
        $this->createsRateLog = $createsRateLog;
        $this->fetchesCurrency = $fetchesCurrency;
    }

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

            $currency_rate_object = new RateObject(
                $request->input('currency_id'),
                number_format( (float) $request->input('selling'), 5, '.', ''),
                $request->input('payment_method_type')
            );

            $this->canCreateRate->passes($currency_rate_object);

            $currency_rate_query = $this->createsRate->execute($currency_rate_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());
        }

    }
}