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

from src.web import deps

router = APIRouter()


@router.get("/")
async def dashboard(request: Request):
    auth = deps.get_auth(request)
    if not auth.is_configured:
        return RedirectResponse(url="/settings", status_code=303)

    db = deps.get_db(request)
    if not await db.get_accounts(active_only=False):
        return RedirectResponse(url="/settings?msg=no_accounts", status_code=303)
    stats = await db.get_stats()
    scheduler = deps.get_scheduler(request)
    return deps.get_templates(request).TemplateResponse(
        request,
        "dashboard.html",
        {
            "stats": stats,
            "scheduler_running": scheduler.is_running,
            "accounts_connected": len(deps.get_pool(request).clients),
        },
    )
