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 database.queries.bot_users import (
    delete_bot_user,
    get_all_bot_users,
    reset_bot_user,
    unblock_bot_user,
)
from database.queries.organizations import get_all_organizations

router = APIRouter(prefix="/bot-users", dependencies=[Depends(require_admin)])


@router.get("", response_class=HTMLResponse)
async def list_bot_users(
    request: Request,
    is_authorized: int | None = None,
    is_blocked: int | None = None,
    org_id: int | None = None,
):
    users = await get_all_bot_users(
        is_authorized=is_authorized,
        is_blocked=is_blocked,
        org_id=org_id,
    )
    orgs = await get_all_organizations()
    return templates.TemplateResponse(
        request=request,
        name="bot_users/list.html",
        context={
            "users": users,
            "orgs": orgs,
            "filter_authorized": is_authorized,
            "filter_blocked": is_blocked,
            "filter_org_id": org_id,
        },
    )


@router.post("/{user_id}/unblock")
async def unblock_user(user_id: int, org_id: int = Form(...)):
    await unblock_bot_user(user_id=user_id, org_id=org_id)
    return RedirectResponse("/admin/bot-users", status_code=303)


@router.post("/{user_id}/reset")
async def reset_user(user_id: int):
    """Сбрасывает авторизацию — пользователь должен заново авторизоваться через бот."""
    await reset_bot_user(user_id=user_id)
    return RedirectResponse("/admin/bot-users", status_code=303)


@router.post("/{user_id}/delete")
async def delete_user(user_id: int):
    """Удаляет пользователя бота полностью."""
    await delete_bot_user(user_id=user_id)
    return RedirectResponse("/admin/bot-users", status_code=303)
