<?php

namespace App\Classes\Modules\Contacts\Services;


use App\Classes\Modules\Contacts\Exceptions\CannotCreateContactException;
use App\Models\Contact;
use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;

class CreatesContact
{
    /** @var Contact */
    private $repository;

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

    /**
     * @param ContactObject $contact
     * @param int $type
     * @param int $referenceId
     * @return Contact
     * @throws CannotCreateContactException
     */
    public function execute(ContactObject $contact, int $type, int $referenceId)
    {
        try{

            $this->repository->type = $type;
            $this->repository->reference_id = $referenceId;
            $this->repository->name = $contact->getName();
            $this->repository->designation = $contact->getDesignation();
            $this->repository->email = $contact->getEmail();
            $this->repository->contact = $contact->getContact();
            $this->repository->save();
            return $this->repository;
        }
        catch (\Exception $exception)
        {
            throw new CannotCreateContactException($exception->getMessage());
        }

    }

}