<?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;

/**
 * Legal service provider for impressum/privacy content updates
 * Simple HMAC-based signature verification for legal content webhooks
 */
final readonly class LegalServiceProvider implements SignatureProvider
{
    public function __construct(
        private HmacService $hmacService
    ) {
    }

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

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

    public function parseSignature(string $headerValue): WebhookSignature
    {
        // Support both prefixed and raw signature formats
        if (str_contains($headerValue, '=')) {
            [$algorithm, $signature] = explode('=', $headerValue, 2);

            return WebhookSignature::create($signature, $algorithm);
        }

        return WebhookSignature::create($headerValue, 'sha256');
    }

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

        return 'sha256=' . $hash->toString();
    }

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

    public function getProviderName(): string
    {
        return 'legal-service';
    }
}
