<?php

namespace App\Classes\Modules\Rules\ControllersLogic;


use App\Classes\Exceptions\CriteriaNotFulfilledException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Rules\DataTransferObjects\CheckEInvoiceRuleDTO;
use App\Classes\Modules\Rules\Services\RuleEvaluator;
use App\Classes\Modules\Rules\Standards\Rules\CanPassEInvoicePromptedRule;
use App\Classes\Modules\Rules\Standards\Rules\CanPassTINRule;
use App\Http\Resources\RuleResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CheckEInvoiceRuleLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Rule Check E-Invoice',
            'message' => 'You have successfully passed all rules evaluated'
        ];
    }

    /** @var RuleEvaluator */
    private $ruleEvaluator;

    /** @var CanPassEInvoicePromptedRule */
    private $canPassEInvoicePromptedRule;

    /** @var CanPassTINRule */
    private $canPassTINRule;

    /**
     * CheckEInvoiceRuleLogic constructor.
     */
    public function __construct(RuleEvaluator $ruleEvaluator, CanPassEInvoicePromptedRule $canPassEInvoicePromptedRule, CanPassTINRule $canPassTINRule)
    {
        $this->ruleEvaluator = $ruleEvaluator;
        $this->canPassEInvoicePromptedRule = $canPassEInvoicePromptedRule;
        $this->canPassTINRule = $canPassTINRule;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     * @throws \App\Classes\Exceptions\CriteriaNotFulfilledException
     */
    public function logic(Request $request) : JsonResponse
    {
        $dto = new CheckEInvoiceRuleDTO($request->all());

        $result = $this->ruleEvaluator->evaluate([
            $this->canPassEInvoicePromptedRule,
            $this->canPassTINRule,
        ], $dto);

        if ($result->failed()) {
            throw new CriteriaNotFulfilledException("- " . implode("<br>- ", $result->messages()));
        }

        return $this->resourceResponse(new RuleResource((object)$result));
    }
}
