<?php

/** @noinspection PhpUndefinedMethodInspection */

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Stories;

use Livewire\Component;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Story;
use DefStudio\GameEngine\Actions\Stories\SaveStory;
use DefStudio\GameEngine\Http\Livewire\Concerns\RedirectsBack;

class Edit extends Component
{
    use RedirectsBack;

    /** @var Story */
    public $story;

    public bool $published;

    public bool $editing;

    public function mount(): void
    {
        Gate::authorize('save', $this->story);
        $this->published = $this->story->published_at !== null;
        $this->editing = !$this->story->exists;
    }

    public function rules(): array
    {
        return [
            'story.title' => ['required', 'string', 'max:255'],
            'story.description' => ['nullable', 'string'],
            'published' => ['nullable', 'boolean'],
        ];
    }

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

    public function save(): void
    {
        $this->validate();

        if ($this->published && $this->story->published_at === null) {
            $this->story->published_at = now();
        }

        SaveStory::run($this->story);

        if ($this->story->wasRecentlyCreated) {
            $this->reflash_back_url();
            $this->redirect(route('game-engine.admin.stories.edit', $this->story));

            return;
        }

        $this->editing = false;
    }
}
