<?php

namespace Signteer\Core\Action\Volunteer;

use Signteer\Core\Action\ActionResult;
use Signteer\Core\Criteria\VolunteerCriteria;
use Signteer\Core\Finder\VolunteerFinder;
use Signteer\Core\Writer\VolunteerWriter;
use Signteer\Core\Repo\SettingRepo;
use Signteer\Core\Event\EventBus;
use Signteer\Core\Event\Volunteer\VolunteerCreated;

final class CreateVolunteer
{
    public $finder = VolunteerFinder::class;
    public $writer = VolunteerWriter::class;
    public $setting = SettingRepo::class;
    public $eventBus = EventBus::class;

    public function __invoke(string $title, string $email, string $phone): ActionResult
    {
        $ret = new ActionResult();

        $title = trim($title);
        if (!strlen($title)) {
            return $ret->addError('__Volunteer name is required.__');
        }

        $email = trim($email);
        if (strlen($email)) {
            $c = (new VolunteerCriteria())->whereEmail('=', $email);
            $exists = $this->finder->exists($c);
            if ($exists) {
                return $ret->addError('__This email address is already in use.__');
            }
        }

        $phone = trim($phone);
        if (strlen($phone)) {
            $c = (new VolunteerCriteria())->wherePhone('=', $phone);
            $exists = $this->finder->exists($c);
            if ($exists) {
                return $ret->addError('__This phone number is already in use.__');
            }
        }

        $id = $this->writer->create($title, $email, $phone);
        $ret->setReturn($id);

        $this->eventBus->emit(new VolunteerCreated($id, $title, $email, $phone));

        return $ret;
    }
}
