"""Webhook processing helpers."""

import hmac
import hashlib
from typing import Optional

from sqlalchemy.orm import Session

from ..config import settings
from ..models import CheckoutSession
from ..repositories import events as event_repo
from ..repositories import checkout_sessions as session_repo


def verify_signature(raw_body: bytes, signature: Optional[str]) -> None:
    if settings.payment_webhook_secret:
        if not signature:
            raise ValueError("Missing signature header")
        expected = hmac.new(
            settings.payment_webhook_secret.encode("utf-8"),
            raw_body,
            hashlib.sha256,
        ).hexdigest()
        if not hmac.compare_digest(expected, signature):
            raise ValueError("Invalid signature")
    elif not settings.allow_unsafe_webhook:
        raise ValueError("Webhook secret not configured")


def is_duplicate_event(db: Session, event_id: str) -> bool:
    return event_repo.get_by_provider_event_id(db, event_id) is not None


def get_session(db: Session, session_id: str) -> Optional[CheckoutSession]:
    return session_repo.get_session(db, session_id)
