<?php

declare(strict_types=1);

namespace BotGuard\Models;

use BotGuard\Core\Model;

/**
 * Deduplicated browser fingerprints. Repeat sightings bump hit_count/last_seen,
 * which the SessionModule uses to recognise returning visitors.
 */
final class Fingerprint extends Model
{
    protected string $table = 'fingerprints';

    /**
     * Record a fingerprint sighting; returns true if it was seen before.
     *
     * @param array<string, mixed> $components
     */
    public function record(string $hash, array $components): bool
    {
        if ($hash === '') {
            return false;
        }

        $existing = $this->firstWhere(['hash' => $hash]);

        if ($existing !== null) {
            $this->db->affectingStatement(
                "UPDATE `{$this->table}` SET `hit_count` = `hit_count` + 1, `last_seen` = ? WHERE `id` = ?",
                [now(), $existing['id']]
            );

            return true;
        }

        $this->create([
            'hash'       => $hash,
            'components' => json_encode($components, JSON_UNESCAPED_SLASHES),
            'hit_count'  => 1,
            'first_seen' => now(),
            'last_seen'  => now(),
        ]);

        return false;
    }
}
