<?php

namespace DefStudio\GameEngine\Http\Livewire\Storytellings;

use Livewire\Component;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Model;
use DefStudio\GameEngine\Models\Storytelling;
use DefStudio\GameEngine\Models\Contracts\WithStorytelling;
use DefStudio\GameEngine\Actions\Storytellings\DeleteStorytelling;

class Manager extends Component
{
    /** @var WithStorytelling&Model */
    public $target;

    protected $listeners = [
        'storytelling.saved' => 'refresh_storytellings',
    ];

    public function render(): View
    {
        return view('game-engine::livewire.admin.storytelling.manager');
    }

    public function refresh_storytellings(): void
    {
        $this->target->unsetRelation('storytellings');
    }

    public function delete(int $storytelling_id): void
    {
        /** @var Storytelling $storytelling */
        $storytelling = $this->target->storytellings()->findOrFail($storytelling_id);

        DeleteStorytelling::run($storytelling);

        $this->refresh_storytellings();
    }
}
