<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Teams;

use Livewire\Component;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Team;
use DefStudio\GameEngine\Actions\Teams\SaveTeam;
use DefStudio\GameEngine\Exceptions\TeamException;
use DefStudio\GameEngine\Http\Livewire\Concerns\RedirectsBack;

class Edit extends Component
{
    use RedirectsBack;

    /** @var Team */
    public $team;

    public function mount(): void
    {
        Gate::authorize('save', $this->team);

        throw_if($this->team->organization_id === null, TeamException::missing_organization());
    }

    public function rules(): array
    {
        return [
            'team.name' => ['required', 'string', 'max:255'],
            'team.organization_id' => ['required'],
        ];
    }

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

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

        SaveTeam::run($this->team);

        $this->redirect_back();
    }
}
