from fastapi import APIRouter, Depends, Query
from typing import Optional
from auth.models import TokenPayload
from auth.dependencies import require_permission
from helpdesk.models import HelpdeskMessage, HelpdeskListResponse
from helpdesk import service

router = APIRouter(prefix="/api/helpdesk", tags=["helpdesk"])


@router.get("", response_model=HelpdeskListResponse)
async def list_messages(
    user_id: Optional[str] = Query(None),
    device_id: Optional[str] = Query(None),
    type: Optional[str] = Query(None),
    _user: TokenPayload = Depends(require_permission("equipment", "view")),
):
    messages = service.list_messages(
        user_id=user_id, device_id=device_id, msg_type=type,
    )
    return HelpdeskListResponse(messages=messages, total=len(messages))


@router.get("/{message_id}", response_model=HelpdeskMessage)
async def get_message(
    message_id: str,
    _user: TokenPayload = Depends(require_permission("equipment", "view")),
):
    return service.get_message(message_id)


@router.patch("/{message_id}/acknowledge", response_model=HelpdeskMessage)
async def toggle_acknowledged(
    message_id: str,
    _user: TokenPayload = Depends(require_permission("equipment", "edit")),
):
    return service.toggle_acknowledged(
        message_id, acknowledged_by=_user.name or _user.email,
    )
