from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError

from src.api.v1.deps import require_admin
from src.db.base import engine
from src.db.models.app_user import AppUser

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


@router.post("/refresh-tree")
async def refresh_tree(current_user: AppUser = Depends(require_admin)):
    """Обновляет MV дерева статей расходов."""
    try:
        async with engine.connect() as conn:
            # CONCURRENTLY требует autocommit-режим.
            conn = await conn.execution_options(isolation_level="AUTOCOMMIT")
            await conn.execute(text("REFRESH MATERIALIZED VIEW CONCURRENTLY v3.mv_expense_item_tree"))
    except SQLAlchemyError as exc:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"Не удалось обновить mv_expense_item_tree: {exc}",
        ) from exc
    return {"status": "ok", "message": "mv_expense_item_tree refreshed"}
