<?php

namespace App\Classes\Modules\HelpMenu\Processors;

use App\Classes\Modules\Accounts\Services\FetchesUser;
use App\Classes\Modules\HelpMenu\Services\FetchesQAUserSource;
use App\Classes\Modules\HelpMenu\Services\CreatesQAUserSource;
use App\Classes\ValueObjects\Constants\QASystemSourceType;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\HelpMenu\DataTransferObjects\QAUserSourceObject;

class UserSourceForQAProcessor
{
    /** @var FetchesUser */
    private $fetchesUser;

    /** @var FetchesQAUserSource */
    private $fetchesQAUserSource;

    /** @var CreatesQAUserSource */
    private $createsQAUserSource;


    /**
     * UserSourceForQAProcessor constructor.
     * @param FetchesUser $fetchesUser
     * @param FetchesQAUserSource $fetchesQAUserSource
     * @param CreatesQAUserSource $createsQAUserSource
     */
    public function __construct(FetchesUser $fetchesUser, FetchesQAUserSource $fetchesQAUserSource, CreatesQAUserSource $createsQAUserSource)
    {
        $this->fetchesUser = $fetchesUser;
        $this->fetchesQAUserSource = $fetchesQAUserSource;
        $this->createsQAUserSource = $createsQAUserSource;
    }

    public function execute($system, $customerMarking, $email){
        $result = [];
        $isFound = false;
        if((int)$system === QASystemSourceType::IZYIM){
            try{
                $query = $this->fetchesUser->execute(['email' => $email]);
                $result['userId'] = $query->id;
                $result['sourceId'] = 0;
                $isFound = true;
            } catch (ResourceNotFoundException $exception){
                $isFound = false;
            }
        }

        if(!$isFound){
            try{
                $query = $this->fetchesQAUserSource->execute(['email' => $email]);
                $result['userId'] = 0;
                $result['sourceId'] = $query->id;
            } catch (ResourceNotFoundException $exception){
                $result['sourceId'] = 0;
            }

            if($result['sourceId'] === 0){
                $new_object = new QAUserSourceObject($system, $customerMarking, $email);
                $query = $this->createsQAUserSource->execute($new_object);
                $result['userId'] = 0;
                $result['sourceId'] = $query->id;
            }
        }

        return $result;
    }
}
