<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Users;

use DefStudio\GameEngine\Enums\Role;
use DefStudio\GameEngine\Models\User;
use DefStudio\WiredTables\WiredTable;
use Illuminate\Database\Eloquent\Builder;
use DefStudio\GameEngine\Actions\Users\DeleteUser;
use Illuminate\Database\Eloquent\Relations\Relation;

class Table extends WiredTable
{
    protected function query(): Builder|Relation
    {
        $query = match (true) {
            \game_engine()->role(Role::super_admin) => \game_engine()->userQuery(),
            !!\game_engine()->user()->current_organization => \game_engine()->user()->current_organization->users(),
            default => \game_engine()->userQuery()->whereHas('organizations', function(Builder $subquery): void {
                $subquery->whereIn('organization_id', \game_engine()->user()->organizations()->pluck('id'));
            }),
        };

        return $query->with('organizations');
    }

    protected function filters(): void
    {
        $organization_query = \game_engine()->role(Role::super_admin)
            ? \game_engine()->organizationQuery()
            : \game_engine()->user()->organizations();

        $this->filter(__('Organization'), 'organization_id')
            ->select($organization_query->pluck('name', 'id')->toArray())
            ->handle(fn(Builder $query, int $organization_id) => $query->whereHas('organizations', fn(Builder $subquery) => $subquery->where('organization_id', $organization_id)));
    }

    protected function columns(): void
    {
        $this->column(__('Name'), 'name')->searchable()->sortable();
        $this->column(__('Email'), 'email')->searchable()->sortable();
        $this->column(__('Organizations'))->view('game-engine::livewire.admin.users.table.role_list');
        $this->column(__('Actions'))->view('game-engine::livewire.admin.users.table.actions');
    }

    public function delete(User $user): void
    {
        DeleteUser::run($user);
    }
}
