from fastapi import APIRouter, Request, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.core.security import verify_payme_auth
from app.services.payme_service import (
    check_perform_transaction,
    create_transaction_handler,
    perform_transaction_handler,
    cancel_transaction_handler,
)

router = APIRouter()


@router.post("/payme")
async def payme_webhook(
    request: Request,
    db: Session = Depends(get_db),
    _: None = Depends(verify_payme_auth),
):
    body = await request.json()
    method = body.get("method")
    params = body.get("params", {})
    request_id = body.get("id")

    if method == "CheckPerformTransaction":
        result = await check_perform_transaction(params)
    elif method == "CreateTransaction":
        result = await create_transaction_handler(db, params)
    elif method == "PerformTransaction":
        result = await perform_transaction_handler(db, params)
    elif method == "CancelTransaction":
        result = await cancel_transaction_handler(db, params)
    else:
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "error": {"code": -32601, "message": "Method not found"},
        }

    return {
        "jsonrpc": "2.0",
        "id": request_id,
        "result": result,
    }