<?php

namespace App\Components\Account;

use App\Models\DeviceLabel;
use App\Support\DeviceInfo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;


class AccountSessions extends Component {
    public ?string $editingSessionId = null;
    public string $deviceLabel = '';

    public function startEdit(string $sessionId): void {
        $this->editingSessionId = $sessionId;

        $existing = DeviceLabel::where('user_id', Auth::id())
            ->where('session_id', $sessionId)
            ->first();

        $this->deviceLabel = $existing?->label ?? '';
    }

    public function saveLabel(): void {
        if (!$this->editingSessionId) {
            return;
        }

        DeviceLabel::updateOrCreate(
            [
                'user_id' => Auth::id(),
                'session_id' => $this->editingSessionId,
            ],
            [
                'label' => trim($this->deviceLabel),
            ]
        );

        $this->reset(['editingSessionId', 'deviceLabel']);
    }

    public function cancelEdit(): void {
        $this->reset(['editingSessionId', 'deviceLabel']);
    }

    /* -------- SESSION ACTIONS -------- */

    public function revokeSession(string $sessionId): void {
        DB::table('sessions')
            ->where('id', $sessionId)
            ->where('user_id', Auth::id())
            ->delete();
    }

    public function logoutOtherSessions(): void {
        DB::table('sessions')
            ->where('user_id', Auth::id())
            ->where('id', '!=', session()->getId())
            ->delete();
    }

    public function render() {
        $sessions = DB::table('sessions')
            ->where('user_id', Auth::id())
            ->orderByDesc('last_activity')
            ->get()
            ->map(function ($session)
            {
                return (object)[
                    ... (array)$session,
                    'device' => DeviceInfo::parse($session->user_agent),
                ];
            });

        $labels = DeviceLabel::where('user_id', Auth::id())
            ->get()
            ->keyBy('session_id');

        return view('components.account.account-sessions', compact('sessions', 'labels'));
    }
}