<?php

namespace DefStudio\GameEngine\Http\Livewire\Users;

use Illuminate\Validation\Rule;
use Illuminate\Contracts\View\View;
use LivewireUI\Modal\ModalComponent;
use DefStudio\GameEngine\Models\User;
use DefStudio\GameEngine\Actions\Users\SaveUser;
use DefStudio\GameEngine\Actions\Users\FindAvailableLocales;
use DefStudio\GameEngine\Http\Livewire\Concerns\ImprovedModal;
use DefStudio\GameEngine\Http\Livewire\Concerns\RedirectsBack;

class Edit extends ModalComponent
{
    use RedirectsBack;
    use ImprovedModal;

    /** @var User */
    public $user;

    public array $available_locales;

    public array $available_roles = [];

    public array $roles = [];

    public function mount(): void
    {
        /** @phpstan-ignore-next-line  */
        $this->user ??= game_engine()->userQuery()->make();

        $this->available_locales = FindAvailableLocales::run();

        SaveUser::make()->authorize($this->user);
    }

    public function rules(): array
    {
        return [
            'user.name' => ['required', 'string', 'max:255'],
            'user.email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->ignore($this->user->id)],
            'user.locale' => ['required', 'string', Rule::in(array_keys($this->available_locales))],
        ];
    }

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

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

        SaveUser::run($this->user);

        if ($this->isModal) {
            if ($this->user->wasRecentlyCreated) {
                $this->emit('user.created', $this->user->id);
            } else {
                $this->emit('user.updated', $this->user->id);
            }

            $this->closeModal();
        } else {
            $this->redirect_back();
        }
    }

    public function switch_to_user(int $user_id): void
    {
        if ($this->isModal) {
            $this->emit('user.switch', $user_id);
            $this->closeModal();
        } else {
            $this->reflash_back_url();
            $this->redirect(route('game-engine.admin.users.edit', $user_id));
        }
    }
}
