<?php

namespace App\Livewire;

use App\Enums\UserRole;
use App\Models\Comment;
use App\Models\User;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class AdminUserSearch extends Component
{
    use WithPagination;

    #[Url(history: true)]
    public $search = '';

    #[Url(history: true)]
    public $discordId = '';

    #[Url(history: true)]
    public $patreon = [];

    #[Url(history: true)]
    public $banned = [];

    public function deleteUserComments(int $userID)
    {
        $user = User::where('id', $userID)
            ->firstOrFail();

        Comment::where('user_id', $user->id)
            ->delete();

        cache()->flush();
    }

    public function render()
    {
        $users = User::when($this->patreon !== [], fn ($query) => $query->whereJsonContains('roles', UserRole::SUPPORTER->value))
            ->when($this->banned !== [], fn ($query) => $query->whereJsonContains('roles', UserRole::BANNED->value))
            ->when($this->search !== '', fn ($query) => $query->where('name', 'like', '%'.$this->search.'%'))
            ->when($this->discordId !== '', fn ($query) => $query->where('discord_id', '=', $this->discordId))
            ->paginate(20);

        return view('livewire.admin-user-search', [
            'users' => $users,
        ]);
    }
}
