<?php

namespace Signteer\Core\Action\Signup;

use Signteer\Core\Action\ActionResult;
use Signteer\Core\Event\EventBus;
use Signteer\Core\Event\Signup\SignupDeleted;
use Signteer\Core\Criteria\TaskCriteria;
use Signteer\Core\Criteria\SignupCriteria;
use Signteer\Core\Criteria\VolunteerCriteria;
use Signteer\Core\Finder\TaskFinder;
use Signteer\Core\Finder\SignupFinder;
use Signteer\Core\Finder\VolunteerFinder;
use Signteer\Core\Writer\SignupWriter;

final class UnassignVolunteer
{
    public $writer = SignupWriter::class;
    public $taskFinder = TaskFinder::class;
    public $signupFinder = SignupFinder::class;
    public $volunteerFinder = VolunteerFinder::class;
    public $eventBus = EventBus::class;

    public function __invoke(int $taskId, int $volunteerId): ActionResult
    {
        $ret = new ActionResult();

        $c = (new SignupCriteria())
            ->whereTaskId('=', $taskId)
            ->whereVolunteerId('=', $volunteerId)
            ;

        $signup = current($this->signupFinder->find($c));
        if (!$signup) {
            return $ret->addError('__Invalid signup.__');
        }

        $signupId = $signup->getId();

        $this->writer->delete($taskId, $volunteerId);
        $this->eventBus->emit(new SignupDeleted($signupId, $taskId, $volunteerId));

        return $ret;
    }
}
