<?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;

final class RegisterVolunteer
{
    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.__');
        }

        $reuse = $this->setting->get('volunteer_reuse_if') ?? 'email';

        $id = null;
        if ('email' === $reuse) {
            $c = (new VolunteerCriteria())->whereEmail('=', $email);
            $ids = $this->finder->findId($c);
            $id = ($ids) ? current($ids) : null;
        }

        if (null === $id) {
            $id = $this->writer->create($title, $email, $phone);
        }

        $ret->setReturn($id);

        // $this->eventBus->emit(new LocationCreated($id, $title));

        return $ret;
    }
}
