<?php

namespace App\Components\Admin\Users;

use App\Models\User\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class UserSessions extends Component {
    use AuthorizesRequests;
    public User $user;

    public function mount(User $user) {
        $this->authorize('manageSessions', $user);
    }

    public function revokeSession(string $sessionId) {
        $this->authorize('manageSessions', $this->user);
        DB::table('sessions')->where('id', $sessionId)->delete();
    }

    public function logoutAll() {
        $this->authorize('manageSessions', $this->user);
        DB::table('sessions')->where('user_id', $this->user->id)->delete();
    }

    public function render() {
        return view('components.admin.users.user-sessions', [
            'sessions' => DB::table('sessions')
                ->where('user_id', $this->user->id)
                ->orderByDesc('last_activity')
                ->get(),
        ]);
    }
}