<?php

namespace DefStudio\GameEngine\Models\Concerns;

use DefStudio\GameEngine\Enums\Feature;
use Illuminate\Database\Eloquent\Model;
use DefStudio\GameEngine\Models\Storytelling;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use DefStudio\GameEngine\Models\Contracts\WithStorytelling;
use DefStudio\GameEngine\Actions\Storytellings\DeleteStorytelling;

trait HasStorytellings
{
    public function storytellings(): MorphMany
    {
        return $this->morphMany(game_engine()->storytellingClass(), 'target');
    }

    public static function bootHasStorytellings(): void
    {
        self::deleting(function(WithStorytelling&Model $model): void {
            $model->loadMissing('storytellings');
            $model->storytellings->each(fn(Storytelling $storytelling) => DeleteStorytelling::run($storytelling));
        });
    }

    public function storytelling_enabled(): bool
    {
        if (Feature::storytelling->disabled()) {
            return false;
        }

        foreach (config('game-engine.storytelling.available_in', []) as $class) {
            if ($this instanceof $class) {
                return true;
            }
        }

        return false;
    }
}
