<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Models\Concerns;

use DefStudio\GameEngine\Models\Story;
use DefStudio\GameEngine\Exceptions\StoryException;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use DefStudio\GameEngine\Events\Stories\TeamSubscribedToStory;
use DefStudio\GameEngine\Events\Stories\TeamUnsubscribedFromStory;

trait HasStories
{
    /**
     * @return BelongsToMany<Story>
     */
    public function stories(): BelongsToMany
    {
        return $this->belongsToMany(Story::class, config('game-engine.stories.subscriptions_table'));
    }

    public function is_subscribed_to_story(Story $story): bool
    {
        return $this->has_attached($story);
    }

    public function subscribe_to_story(Story $story): self
    {
        throw_if($story->organization_id !== $this->organization_id, StoryException::organization_membership_failure());

        throw_if($this->is_subscribed_to_story($story), StoryException::already_subscribed());

        $this->stories()->attach($story);

        TeamSubscribedToStory::dispatch($this, $story);

        return $this;
    }

    public function unsubscribe_from_story(Story $story): void
    {
        throw_if(!$this->is_subscribed_to_story($story), StoryException::team_subscription_failure());

        $this->stories()->detach($story);

        TeamUnsubscribedFromStory::dispatch($this, $story);
    }
}
