<?php

namespace App\Livewire\Admin;

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

/**
 * "Where am I signed in", for an operator.
 *
 * Deliberately not the portal's component with a guard passed in: two
 * identities, two guards, two tables (R21), and a component that took the guard
 * as input would be one forged property away from ending a customer's sessions
 * from the console. The view is shared, because markup is not identity.
 */
class Sessions extends Component
{
    use ResolvesOperator;

    private const GUARD = 'operator';

    public function end(string $uuid): void
    {
        if (! $operator = $this->currentOperator()) {
            return;
        }

        app(SessionRegistry::class)->end(self::GUARD, (int) $operator->getKey(), $uuid);

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

    /** Raised by the confirmation modal (R23), never called from the markup. */
    #[On('sessions-end-others-confirmed')]
    public function endOthers(): void
    {
        if (! $operator = $this->currentOperator()) {
            return;
        }

        $registry = app(SessionRegistry::class);
        $count = $registry->endOthers(self::GUARD, (int) $operator->getKey(), $registry->currentUuid());

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

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

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