<?php

namespace App\Classes\Modules\Accounts\ControllersLogic;

use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Accounts\Services\CompletesEmailVerificationAttempt;
use App\Classes\Modules\Accounts\Services\FetchesEmailVerificationAttempt;
use App\Classes\Modules\Accounts\Services\VerifiesUser;
use App\Classes\Modules\Accounts\Standards\Criteria\EmailVerificationActiveAttemptExists;
use App\Models\UserEmailVerification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserEmailVerificationLogic extends AbstractControllerLogic
{

    public function notification(): array
    {
        return [
            'title' => 'Email Verification',
            'message' => 'You have successfully verified your email address'
        ];
    }

    /** @var emailVerificationActiveAttemptExists */
    private $emailVerificationActiveAttemptExists;

    /** @var CompletesEmailVerificationAttempt */
    private $completesEmailVerificationAttempt;

    /** @var FetchesEmailVerificationAttempt */
    private $fetchesEmailVerificationAttempt;

    /** @var VerifiesUser */
    private $verifiesUser;

    /**
     * UserEmailVerificationLogic constructor.
     * @param EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists
     * @param CompletesEmailVerificationAttempt $completesEmailVerificationAttempt
     * @param FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt
     * @param VerifiesUser $verifiesUser
     */
    public function __construct(EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists, CompletesEmailVerificationAttempt $completesEmailVerificationAttempt, FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt, VerifiesUser $verifiesUser)
    {
        $this->emailVerificationActiveAttemptExists = $emailVerificationActiveAttemptExists;
        $this->completesEmailVerificationAttempt = $completesEmailVerificationAttempt;
        $this->fetchesEmailVerificationAttempt = $fetchesEmailVerificationAttempt;
        $this->verifiesUser = $verifiesUser;
    }

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

        $token = $request->input('token');

        $this->emailVerificationActiveAttemptExists->execute($token);

        /** @var UserEmailVerification $attempt */
        $attempt = $this->fetchesEmailVerificationAttempt->execute(['token' => $token]);

        $this->completesEmailVerificationAttempt->execute($attempt);

        $this->verifiesUser->execute($attempt->user);

        return $this->response([]);
    }

}