"""Webhook endpoints for payment processor callbacks."""

from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session

from ..db import get_db
from ..schemas import WebhookEventIn
from ..services import checkout_service, webhook_service

router = APIRouter(prefix="/v1/webhooks", tags=["webhooks"])


@router.post("/payment-processor", status_code=status.HTTP_200_OK)
async def payment_processor_webhook(request: Request, db: Session = Depends(get_db)):
    """Accept payment processor events and update session status idempotently."""

    raw_body = await request.body()
    signature = request.headers.get("X-Signature")
    try:
        webhook_service.verify_signature(raw_body, signature)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))

    payload = await request.json()
    event = WebhookEventIn(**payload)

    if webhook_service.is_duplicate_event(db, event.event_id):
        return {"received": True, "idempotent": True}

    session = webhook_service.get_session(db, event.session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Checkout session not found")

    if event.status not in {"paid", "failed"}:
        raise HTTPException(status_code=400, detail="Unsupported status")

    checkout_service.mark_paid(db, session, event.status, event.event_id, payload)
    return {"received": True, "idempotent": False}
