"""/api/comments — the global board + bell (04 "thin routers": every
rule lives in services/comments.py; this layer only shapes HTTP and
translates ServiceError -> the structured ApiError triple).

Routes:
  GET    /api/comments                    board window + real badge count
  POST   /api/comments                    post (attributed to effective user)
  POST   /api/comments/{id}/resolve       resolve (re-stamps; B9)
  POST   /api/comments/{id}/reopen        reopen (no-op if open; B9)
  DELETE /api/comments/{id}               delete (author / super-admin; 403 else)
"""

from __future__ import annotations

import uuid

from fastapi import APIRouter
from pydantic import BaseModel

from app.routers.deps import ActorDep, ApiError, SessionDep
from app.services import comments as comments_svc
from app.services.errors import ServiceError

router = APIRouter()


def _run(fn, *args, **kwargs):
    try:
        return fn(*args, **kwargs)
    except ServiceError as exc:
        raise ApiError(exc.status, exc.code, exc.summary, exc.detail) from exc


class CommentCreate(BaseModel):
    body: str = ""


@router.get("/api/comments")
def list_comments(session: SessionDep, actor: ActorDep) -> dict:
    return _run(comments_svc.list_comments, session, actor)


@router.post("/api/comments")
def post_comment(session: SessionDep, actor: ActorDep, body: CommentCreate) -> dict:
    row = _run(comments_svc.post_comment, session, actor, body.body)
    return {"ok": True, "comment": row}


@router.post("/api/comments/{comment_id}/resolve")
def resolve_comment(
    session: SessionDep, actor: ActorDep, comment_id: uuid.UUID
) -> dict:
    row = _run(comments_svc.resolve_comment, session, actor, comment_id)
    return {"ok": True, "comment": row}


@router.post("/api/comments/{comment_id}/reopen")
def reopen_comment(
    session: SessionDep, actor: ActorDep, comment_id: uuid.UUID
) -> dict:
    row = _run(comments_svc.reopen_comment, session, actor, comment_id)
    return {"ok": True, "comment": row}


@router.delete("/api/comments/{comment_id}")
def delete_comment(
    session: SessionDep, actor: ActorDep, comment_id: uuid.UUID
) -> dict:
    return _run(comments_svc.delete_comment, session, actor, comment_id)
