# retoor <retoor@molodetz.nl>

import logging
from typing import Annotated

from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse, RedirectResponse

from devplacepy.dependencies import json_or_form
from devplacepy.models import TelegramPairForm
from devplacepy.responses import wants_json
from devplacepy.routers.profile._shared import resolve_customization_target
from devplacepy.services.audit import record as audit
from devplacepy.services.telegram import store

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


@router.post("/{username}/telegram")
async def telegram_pairing(
    request: Request,
    username: str,
    data: Annotated[TelegramPairForm, Depends(json_or_form(TelegramPairForm))],
) -> None:
    target, denied = resolve_customization_target(request, username)
    if denied is not None:
        return denied
    url = f"/profile/{target['username']}"
    if data.action == "unpair":
        store.unpair(target["uid"])
        audit.record(
            request,
            "telegram.unpair",
            target_type="user",
            target_uid=target["uid"],
            target_label=target["username"],
            summary=f"unpaired Telegram for {target['username']}",
            links=[audit.target("user", target["uid"], target["username"])],
        )
        payload = {"ok": True, "paired": False}
    else:
        issued = store.issue_code(target["uid"])
        audit.record(
            request,
            "telegram.pair.request",
            target_type="user",
            target_uid=target["uid"],
            target_label=target["username"],
            summary=f"requested a Telegram pairing code for {target['username']}",
            links=[audit.target("user", target["uid"], target["username"])],
        )
        payload = {
            "ok": True,
            "paired": False,
            "code": issued["code"],
            "expires_at": issued["expires_at"],
            "ttl_minutes": issued["ttl_minutes"],
        }
    if wants_json(request):
        return JSONResponse(payload)
    return RedirectResponse(url=url, status_code=302)
