<?php

namespace DefStudio\GameEngine\Http\Livewire\Organizations;

use Livewire\Component;
use Illuminate\Contracts\View\View;
use DefStudio\GameEngine\Enums\Role;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\User;
use DefStudio\GameEngine\Models\Organization;
use DefStudio\GameEngine\Actions\Organizations\SaveOrganization;

class Edit extends Component
{
    /** @var Organization */
    public $organization;

    public string|null $role_under_creation = null;

    protected $listeners = [
        'user.created' => 'handle_user_created',
        'user.switch' => 'handle_user_switch',
    ];

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

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

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

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

        SaveOrganization::run($this->organization);

        $this->redirect(route('game-engine.admin.organizations.edit', $this->organization));
    }

    public function handle_user_created(int $user_id): void
    {
        /** @var User $user */
        $user = game_engine()->userQuery()->find($user_id);

        $role = Role::from($this->role_under_creation);

        $user->subscribe_to_organization($this->organization, $role);
        $this->emit('user.subscribed', $user->id, $this->organization->id);
    }

    public function handle_user_switch(int $user_id): void
    {
        /** @var User $user */
        $user = game_engine()->userQuery()->find($user_id);

        $role = Role::from($this->role_under_creation);

        $user->subscribe_to_organization($this->organization, $role);
        $this->emit('user.subscribed', $user->id, $this->organization->id);
    }
}
