<?php

namespace App\Classes\Modules\Accounts\Services;

use App\Classes\Exceptions\Common\ServiceException;
use App\Models\UserEmailVerification;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\MassAssignmentException;
use Illuminate\Database\Eloquent\Model;

class CreatesEmailVerificationAttempt {
    private const EMAIL_VERIFICATION_PREFIX = 'EMAIL';

    /** @var UserEmailVerification */
    private $repository;

    /**
     * CreatesEmailVerificationForCustomer constructor.
     *
     * @param UserEmailVerification $repository
     */
    public function __construct(UserEmailVerification $repository) {
        $this->repository = $repository;
    }

    /**
     * @param string $emailAddress
     *
     * @throws ServiceException
     *
     * @return UserEmailVerification|Model
     */
    public function execute(string $emailAddress): UserEmailVerification {

        // verify if the email address already has a pending verification
        $attempts = $this->repository->where('email', $emailAddress)
            ->where('is_active', true)
            ->where('is_complete', false);


        $attemptExists = count($attempts->get()) > 0 ? true : false;

        try {
            // if a previous attempt exists, then disable any previous attempts
            if ($attemptExists === true) {
                $attempts->update(['is_active' => false, 'is_complete' => false]);
            }

            // generate a token
            $token = md5(uniqid(self::EMAIL_VERIFICATION_PREFIX, true) . Carbon::now()->timestamp);

            // create the email verification for the customer
            return $this->repository->create([
                'email'          => $emailAddress,
                'token'          => $token,
                'is_complete'    => false,
                'is_active'      => true,
            ]);
        } catch (MassAssignmentException $exception) {
            throw new ServiceException($exception->getMessage());
        }
    }
}
