from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse

from admin.auth import require_admin
from admin.templates_env import templates
from bot.bot_instance import get_bot
from database.queries.bot_users import get_bot_user_by_max_id
from database.queries.message_log import get_chat_list, get_message_log, log_message

router = APIRouter(prefix="/chat-log", dependencies=[Depends(require_admin)])


@router.get("", response_class=HTMLResponse)
async def chat_list(request: Request):
    chats = await get_chat_list()
    return templates.TemplateResponse(
        request=request, name="chat_log/list.html", context={"chats": chats}
    )


@router.get("/{max_user_id}", response_class=HTMLResponse)
async def chat_history(request: Request, max_user_id: int):
    messages = await get_message_log(max_user_id=max_user_id, limit=200)
    bot_user = await get_bot_user_by_max_id(max_user_id)
    return templates.TemplateResponse(
        request=request,
        name="chat_log/history.html",
        context={
            "messages": messages,
            "max_user_id": max_user_id,
            "bot_user": bot_user,
        },
    )


@router.post("/{max_user_id}/send")
async def send_message_to_user(max_user_id: int, text: str = Form(...)):
    bot_user = await get_bot_user_by_max_id(max_user_id)
    if bot_user is None or not bot_user.get("max_chat_id"):
        return RedirectResponse(f"/admin/chat-log/{max_user_id}", status_code=303)

    chat_id = bot_user["max_chat_id"]
    bot = get_bot()
    await bot.send_message(chat_id=chat_id, text=text)
    await log_message(
        direction="out",
        max_user_id=max_user_id,
        max_chat_id=chat_id,
        message_id=None,
        text=text,
    )
    return RedirectResponse(f"/admin/chat-log/{max_user_id}", status_code=303)
