<?php

namespace App\Classes\Modules\Accounts\ControllersLogic;

use App\Classes\Exceptions\ResourceConflictException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Accounts\Processors\CreateUserProcessor;
use App\Classes\Modules\Accounts\Processors\GenerateEmailVerificationAttemptProcessor;
use App\Classes\Modules\Companies\DataTransferObjects\EmploymentObject;
use App\Classes\Modules\Companies\Processors\AssignEmployeeProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\UserResource;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AddNewMemberLogic extends AbstractControllerLogic
{

    public function notification(): array
    {
        return [
            'title' => 'Updated Email',
            'message' => 'Successfully updated email'
        ];
    }

    /**
     * @var AssignEmployeeProcessor
     */
    private $assignEmployeeProcessor;

    /**
     * @var GenerateEmailVerificationAttemptProcessor
     */
    private $generateEmailVerificationAttemptProcessor;

    /**
     * AddNewMemberLogic constructor.
     * @param AssignEmployeeProcessor $assignEmployeeProcessor
     * @param GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor
     */
    public function __construct(AssignEmployeeProcessor $assignEmployeeProcessor, GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor)
    {
        $this->assignEmployeeProcessor = $assignEmployeeProcessor;
        $this->generateEmailVerificationAttemptProcessor = $generateEmailVerificationAttemptProcessor;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ResourceConflictException
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request): JsonResponse
    {
        try {
            $user = Auth::user()->replicate();
            $user->email = $request->input('email');
            $user->status = ApprovalStatus::PENDING_VERIFICATION;
            $user->save();
        } catch (QueryException $exception){
            throw new ResourceConflictException('Unable to change your email address as it already exists');
        }

        if($company = Auth::user()->companyModule()->first()){
            $Object = new EmploymentObject($company, $user);
            $this->assignEmployeeProcessor->execute($Object);
        }

        $this->generateEmailVerificationAttemptProcessor->execute($user);

        return $this->resourceResponse(new UserResource($user));
    }
}
