# retoor <retoor@molodetz.nl>

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

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

VOTABLE = {"post", "comment", "gist", "project", "quiz"}


@router.post("/{target_type}/{target_uid}")
async def vote(
    request: Request,
    target_type: str,
    target_uid: str,
    data: Annotated[VoteForm, Depends(json_or_form(VoteForm))],
):
    user = require_user(request)
    if target_type not in VOTABLE:
        return JSONResponse({"error": "Invalid target"}, status_code=400)
    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)

    return RedirectResponse(url=redirect_back(request), status_code=302)
