<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Teams;

use DefStudio\GameEngine\Enums\Role;
use DefStudio\GameEngine\Models\Team;
use DefStudio\GameEngine\Models\User;
use DefStudio\WiredTables\WiredTable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use DefStudio\WiredTables\Configurations\TableConfiguration;

class UsersTable extends WiredTable
{
    /** @var Team */
    public $team;

    protected function configure(TableConfiguration $configuration): void
    {
        $configuration
            ->pageSize(10)
            ->groupFilters(false);
    }

    protected function filters(): void
    {
        $this->filter(__('Role'), 'role')
            ->select(collect([Role::master, Role::player])->mapWithKeys(fn(Role $role): array => [$role->value => $role->label(2)]))
            ->placeholder(__('All Roles'))
            ->handle(fn(BelongsToMany $query, string $role) => $query->wherePivot('role', $role));

        $this->filter(__('Display'), 'display')
            ->select(['subscribed' => __('Display Subscribed')])
            ->placeholder(__('Display All Users'))
            ->handle(fn(BelongsToMany $query) => $query->whereHas('teams', fn(Builder $subquery) => $subquery->where('teams.id', $this->team->id)));
    }

    protected function query(): Builder|Relation
    {
        return $this->team->organization
            ->users()
            ->wherePivot('role', '!=', Role::admin)
            ->with('teams');
    }

    protected function columns(): void
    {
        $this->column(__('Name'), 'name')->searchable()->sortable();
        $this->column(__('Email'), 'email')->searchable()->sortable();
        $this->column(__('Role'))->view('game-engine::livewire.admin.teams.users-table.role', ['team' => $this->team]);
        $this->column(__('Actions'))->view('game-engine::livewire.admin.teams.users-table.actions', ['team' => $this->team]);
    }

    public function subscribe(int $user_id): void
    {
        /** @var User $user */
        $user = $this->team->organization->users()->findOrFail($user_id);
        $user->subscribe_to_team($this->team);
    }

    public function unsubscribe(int $user_id): void
    {
        /** @var User $user */
        $user = $this->team->organization->users()->findOrFail($user_id);
        $user->unsubscribe_from_team($this->team);
    }
}
