<?php

namespace DefStudio\GameEngine\Listeners\Organizations;

use DefStudio\GameEngine\Models\Team;
use DefStudio\GameEngine\Events\Organizations\UserUnsubscribedFromOrganization;

class UserUnsubscribedFromOrganizationListener
{
    public function handle(UserUnsubscribedFromOrganization $event): void
    {
        $event->user->teams
            ->where('organization_id', $event->organization->id)
            ->each(fn(Team $team) => $event->user->unsubscribe_from_team($team));

        if ($event->user->current_organization_id === $event->organization->id) {
            $event->user->current_organization_id = null;
            $event->user->unsetRelation('current_organization');
        }

        $event->user->unsetRelation('organizations');
        $event->user->unsetRelation('teams');
        $event->user->unsetRelation('current_teams');

        $event->organization->unsetRelation('users');
        $event->organization->unsetRelation('admins');
        $event->organization->unsetRelation('masters');
        $event->organization->unsetRelation('players');
    }
}
