<?php

namespace App\Support;

use App\Models\User;
use Illuminate\Http\Request;

/**
 * Resolves the "viewer" identity for a request: either an authenticated user
 * or an anonymous guest identified by an opaque X-Guest-Id header (a UUID the
 * client stores in localStorage). Used for per-user/per-session unlock state.
 */
class Viewer
{
    public function __construct(
        public readonly ?int $userId,
        public readonly ?string $guestId,
    ) {
    }

    public static function fromRequest(Request $request): self
    {
        $user = $request->user();
        if ($user instanceof User) {
            return new self($user->id, null);
        }

        $guest = $request->header('X-Guest-Id');
        // Only accept plausible, bounded identifiers.
        if (is_string($guest) && preg_match('/^[A-Za-z0-9\-]{8,64}$/', $guest)) {
            return new self(null, $guest);
        }

        return new self(null, null);
    }

    public function hasIdentity(): bool
    {
        return $this->userId !== null || $this->guestId !== null;
    }
}
