"""Tests for webhook signature verification."""
import hashlib
import hmac
import time

from relayway.webhook import verify_signature


def test_verify_signature_returns_true_for_valid_signature():
    secret = "whsec_test_secret"
    payload = '{"to": "test@example.com"}'
    timestamp = int(time.time())

    # Generate valid signature
    message = f"{timestamp}.{payload}"
    signature = hmac.new(
        secret.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()

    assert verify_signature(secret, signature, timestamp, payload) is True


def test_verify_signature_returns_false_for_invalid_signature():
    secret = "whsec_test_secret"
    payload = '{"to": "test@example.com"}'
    timestamp = int(time.time())

    assert verify_signature(secret, "invalid_signature", timestamp, payload) is False


def test_verify_signature_returns_false_for_wrong_secret():
    secret = "whsec_test_secret"
    wrong_secret = "whsec_wrong_secret"
    payload = '{"to": "test@example.com"}'
    timestamp = int(time.time())

    # Generate signature with correct secret
    message = f"{timestamp}.{payload}"
    signature = hmac.new(
        secret.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()

    # Verify with wrong secret
    assert verify_signature(wrong_secret, signature, timestamp, payload) is False


def test_verify_signature_returns_false_for_tampered_payload():
    secret = "whsec_test_secret"
    payload = '{"to": "test@example.com"}'
    tampered_payload = '{"to": "attacker@evil.com"}'
    timestamp = int(time.time())

    # Generate signature for original payload
    message = f"{timestamp}.{payload}"
    signature = hmac.new(
        secret.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()

    # Verify with tampered payload
    assert verify_signature(secret, signature, timestamp, tampered_payload) is False


def test_verify_signature_returns_false_for_wrong_timestamp():
    secret = "whsec_test_secret"
    payload = '{"to": "test@example.com"}'
    timestamp = int(time.time())
    wrong_timestamp = timestamp - 1000

    # Generate signature with correct timestamp
    message = f"{timestamp}.{payload}"
    signature = hmac.new(
        secret.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()

    # Verify with wrong timestamp
    assert verify_signature(secret, signature, wrong_timestamp, payload) is False
