<?php

namespace App\Models;

use App\Models\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One signed-in browser session, as something a person can see and end.
 *
 * Keyed by its own uuid, which is kept inside the session payload rather than
 * by the session id. Laravel rotates the session id on every sign-in and on
 * every regenerate() — a row keyed by that id loses sight of the session it
 * describes within a request or two, and the operator is then offered a list of
 * sessions that no longer exist next to the one they are sitting in.
 *
 * `session_id` is still stored, because ending a session means deleting the
 * framework's own row: the next request from that browser finds nothing and is
 * signed out. It is refreshed from the uuid on every request instead of being
 * trusted to stay put.
 */
class LoginSession extends Model
{
    use HasUuid;

    /** Where the uuid lives inside the session payload. */
    public const KEY = 'login_session_uuid';

    protected $fillable = [
        'device_id', 'session_id', 'ip_address', 'last_seen_at',
    ];

    protected function casts(): array
    {
        return ['last_seen_at' => 'datetime'];
    }

    public function device(): BelongsTo
    {
        return $this->belongsTo(UserDevice::class, 'device_id');
    }
}
