<?php

namespace App\Livewire;

use App\Services\Devices\SessionRegistry;
use Livewire\Attributes\On;
use Livewire\Component;

/**
 * "Where am I signed in", for a customer.
 *
 * The console has its own (App\Livewire\Admin\Sessions) rather than this one
 * being reused with a guard argument. Two identities, two guards, two tables
 * (R21) — and a component that took the guard as input would be one forged
 * property away from listing and ending the other side's sessions.
 *
 * The view is shared, because markup is not identity.
 */
class Sessions extends Component
{
    private const GUARD = 'web';

    public function end(string $uuid): void
    {
        app(SessionRegistry::class)->end(self::GUARD, (int) auth()->id(), $uuid);

        $this->dispatch('notify', message: __('sessions.ended'));
    }

    /**
     * Raised by the confirmation modal (R23), never called from the markup.
     * The check stays here, at the one place that already had it.
     */
    #[On('sessions-end-others-confirmed')]
    public function endOthers(): void
    {
        $registry = app(SessionRegistry::class);
        $count = $registry->endOthers(self::GUARD, (int) auth()->id(), $registry->currentUuid());

        $this->dispatch('notify', message: __('sessions.ended_others', ['n' => $count]));
    }

    public function render()
    {
        $registry = app(SessionRegistry::class);
        $current = $registry->currentUuid();

        return view('livewire.sessions', [
            'sessions' => $registry->for(self::GUARD, (int) auth()->id(), $current),
            'confirmComponent' => 'confirm-end-other-sessions',
        ]);
    }
}
