# retoor <retoor@molodetz.nl>

import logging
from typing import Annotated
from fastapi import APIRouter, Request, Form
from fastapi.responses import RedirectResponse, JSONResponse
from devplacepy.utils import require_user
from devplacepy.content import apply_vote
from devplacepy.models import VoteForm

logger = logging.getLogger(__name__)
router = APIRouter()


@router.post("/{target_type}/{target_uid}")
async def vote(
    request: Request,
    target_type: str,
    target_uid: str,
    data: Annotated[VoteForm, Form()],
):
    user = require_user(request)
    result = apply_vote(request, user, target_type, target_uid, data.value)

    if request.headers.get("x-requested-with") == "fetch":
        logger.debug(
            "ajax vote response target=%s/%s net=%s value=%s",
            target_type,
            target_uid,
            result["net"],
            result["value"],
        )
        return JSONResponse(result)

    referer = request.headers.get("Referer", "/feed")
    return RedirectResponse(url=referer, status_code=302)
