<?php

declare(strict_types=1);

final class MyronAnalyticsSessionHashService
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function getDailySalt(?DateTimeImmutable $now = null): string
    {
        $now = ($now ?? new DateTimeImmutable('now', new DateTimeZone('UTC')))->setTimezone(new DateTimeZone('UTC'));
        $date = $now->format('Y-m-d');
        $statement = $this->pdo->prepare('SELECT salt_value FROM analytics_daily_salts WHERE salt_date = :salt_date LIMIT 1');
        $statement->execute([':salt_date' => $date]);
        $salt = $statement->fetchColumn();
        if (is_string($salt) && $salt !== '') {
            return $salt;
        }

        $salt = hash('sha256', $date . '|' . bin2hex(random_bytes(16)));
        $insert = $this->pdo->prepare(
            'INSERT INTO analytics_daily_salts (salt_date, salt_value, expires_at, created_at)
             VALUES (:salt_date, :salt_value, :expires_at, :created_at)'
        );
        $insert->execute([
            ':salt_date' => $date,
            ':salt_value' => $salt,
            ':expires_at' => $now->modify('+1 day')->format('Y-m-d H:i:s'),
            ':created_at' => myronNow(),
        ]);

        return $salt;
    }

    public function computeSessionHash(string $ip, string $uaFamily, string $hostname, ?DateTimeImmutable $now = null): string
    {
        $input = $this->getDailySalt($now) . '|' . trim($ip) . '|' . trim($uaFamily) . '|' . strtolower(trim($hostname));
        return hash('sha256', $input);
    }
}
