<?php

declare(strict_types=1);

namespace App\Framework\Webhook\Security\Providers;

use App\Framework\Core\ValueObjects\HashAlgorithm;
use App\Framework\Encryption\HmacService;
use App\Framework\Webhook\ValueObjects\WebhookSignature;

/**
 * Generic HMAC signature provider using framework's Hash system
 * Supports standard HMAC verification with configurable algorithms
 */
final readonly class GenericHmacProvider implements SignatureProvider
{
    public function __construct(
        private HmacService $hmacService,
        private HashAlgorithm $algorithm = HashAlgorithm::SHA256
    ) {
    }

    public function verify(string $payload, string $signatureHeader, string $secret): bool
    {
        $signature = $this->parseSignature($signatureHeader);

        return $this->hmacService->verifyHmacString(
            $payload,
            $signature->toString(),
            $secret,
            $this->algorithm
        );
    }

    public function parseSignature(string $headerValue): WebhookSignature
    {
        return WebhookSignature::fromHeader($headerValue);
    }

    public function generateSignature(string $payload, string $secret): string
    {
        $hash = $this->hmacService->generateHmac($payload, $secret, $this->algorithm);

        return $this->algorithm->value . '=' . $hash->toString();
    }

    public function getSignatureHeader(): string
    {
        return 'X-Signature';
    }

    public function getProviderName(): string
    {
        return 'generic';
    }
}
