<?php

namespace Ignite\Core\Listeners;

use Ignite\Core\Entities\Group;
use Ignite\Core\Entities\User;
use Illuminate\Auth\Events\Registered;

class AssignUserToGroup
{
    /**
     * When a user enrolls event.
     *
     * @param Registered $event
     */
    public function handle($event)
    {
        $group = $this->getParticipantGroup();

        /** @var User $user */
        $user = $event->user;

        // Only attach if user has no group at all
        if ($user->groups->isEmpty()) {
            $user->groups()->attach($group->getKey());
            $user->save();
        }
    }

    /**
     * The the Group model for a Participant.
     *
     * @return mixed
     */
    protected function getParticipantGroup()
    {
        $securityGroup =  config('core.participant.enrollment.default_security_group');

        return Group::query()->where('key', $securityGroup)->first();
    }
}
