# retoor <retoor@molodetz.nl>

import logging
from typing import Annotated

from fastapi import Depends, APIRouter, Request

from devplacepy.models import IssueStatusForm
from devplacepy.responses import action_result, json_error
from devplacepy.services.audit import record as audit
from devplacepy.services.gitea import runtime
from devplacepy.services.gitea.client import GiteaError
from devplacepy.services.gitea.config import gitea_config
from devplacepy.utils import is_admin, require_user
from devplacepy.dependencies import json_or_form

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

@router.post("/{number}/status")
async def status_issue(
    request: Request, number: int, data: Annotated[IssueStatusForm, Depends(json_or_form(IssueStatusForm))]
):
    user = require_user(request)
    if not is_admin(user):
        audit.record(
            request,
            "issue.status",
            user=user,
            result="denied",
            target_type="issue",
            target_uid=str(number),
            summary=f"{user['username']} denied changing status of issue #{number}",
        )
        return json_error(403, "Admins only")
    if not gitea_config().is_configured:
        return json_error(503, "The issue tracker is not configured")
    try:
        await runtime.get_client().set_state(number, data.status)
    except GiteaError as exc:
        logger.warning("Could not change status of #%s: %s", number, exc)
        audit.record(
            request,
            "issue.status",
            user=user,
            result="failure",
            target_type="issue",
            target_uid=str(number),
            summary=f"Failed to change status of issue #{number}: {exc}",
        )
        return json_error(exc.status or 502, "Could not change the status")

    audit.record(
        request,
        "issue.status",
        user=user,
        target_type="issue",
        target_uid=str(number),
        new_value=data.status,
        summary=f"{user['username']} set issue #{number} to {data.status}",
        metadata={"number": number, "state": data.status},
        links=[audit.target("issue", str(number))],
    )
    logger.info("Issue #%s set to %s by %s", number, data.status, user["username"])
    return action_result(request, f"/issues/{number}", data={"state": data.status})
