<?php

namespace App\Components\Admin\Users;

use App\Models\User\User;
use App\Services\HistoryService;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class UserSessions extends Component {
    public User $user;

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

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

        $history->add($this->user, 'Session revoked', [
            'session_id' => $sessionId,
        ]);
    }

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

        $history->add($this->user, 'All sessions revoked (forced logout)', [
            'sessions_removed' => $count,
        ]);
    }

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