<?php

namespace App\Services\Elections;

class VoteIntegrityService
{
    /**
     * Generate a random salt for vote hashing.
     */
    public function generateSalt(): string
    {
        return bin2hex(random_bytes(32)); // 64 hex chars
    }

    /**
     * Compute a SHA-256 integrity hash for a vote.
     *
     * The hash covers: election_id, position_id, vote_data (JSON), and salt.
     * This ensures any modification to the vote payload is detectable.
     */
    public function computeVoteHash(int $electionId, int $positionId, array $voteData, string $salt): string
    {
        $input = implode('|', [
            $electionId,
            $positionId,
            json_encode($voteData),
            $salt,
        ]);

        return hash('sha256', $input);
    }

    /**
     * Verify a vote's integrity hash.
     */
    public function verifyVoteHash(int $electionId, int $positionId, array $voteData, string $salt, string $expectedHash): bool
    {
        $computedHash = $this->computeVoteHash($electionId, $positionId, $voteData, $salt);
        return hash_equals($expectedHash, $computedHash);
    }

    /**
     * Generate a certification signature hash.
     * SHA-256(election_id + user_id + timestamp)
     */
    public function computeCertificationHash(int $electionId, int $userId, string $timestamp): string
    {
        return hash('sha256', implode('|', [$electionId, $userId, $timestamp]));
    }
}
