from fastapi import APIRouter, Depends, HTTPException, Query

from app.core.dependencies import require_admin, require_superuser
from app.modules.admin.schemas import (
    AdminSettingsPatchIn,
    AdminRevealSecretIn,
    AdminUiActivityIn,
    AdminUserCreateIn,
    AdminUserPasswordPatchIn,
    AdminUserPatchIn,
)
from app.modules.admin.service import (
    create_admin_user,
    delete_admin_user,
    get_admin_settings,
    get_admin_summary,
    get_install_secrets,
    get_diagnostics_report,
    get_server_log_tail,
    list_activity_feed,
    list_admin_users,
    patch_admin_settings,
    patch_user,
    record_ui_activity,
    reveal_secret,
    reset_user_password,
)
from app.modules.analytics.service import get_admin_dashboard_metrics

router = APIRouter()


@router.get("/users")
async def list_users_route(
    page: int = Query(default=1, ge=1),
    limit: int = Query(default=20, ge=1, le=100),
    _admin=Depends(require_admin),
):
    return list_admin_users(page, limit)


@router.patch("/users/{user_id}")
async def patch_user_route(
    user_id: str,
    payload: AdminUserPatchIn,
    admin=Depends(require_admin),
):
    if payload.is_superuser is not None and not admin.is_superuser:
        raise HTTPException(status_code=403, detail="SUPERUSER_ONLY")
    try:
        return patch_user(admin, user_id, payload.role, payload.status, payload.is_superuser)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))


@router.post("/users")
async def create_user_route(payload: AdminUserCreateIn, admin=Depends(require_superuser)):
    try:
        return create_admin_user(
            admin,
            email=payload.email,
            password=payload.password,
            role=payload.role,
            is_superuser=payload.is_superuser,
            status=payload.status,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))


@router.patch("/users/{user_id}/password")
async def reset_user_password_route(
    user_id: str, payload: AdminUserPasswordPatchIn, admin=Depends(require_superuser)
):
    try:
        return reset_user_password(admin, user_id, payload.password)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))


@router.delete("/users/{user_id}")
async def delete_user_route(user_id: str, admin=Depends(require_superuser)):
    try:
        return delete_admin_user(admin, user_id)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))


@router.get("/summary")
async def summary_route(_admin=Depends(require_admin)):
    return get_admin_summary()


@router.get("/stats")
async def stats_route(_admin=Depends(require_admin)):
    return get_admin_dashboard_metrics()


@router.get("/settings")
async def admin_settings_route(_admin=Depends(require_superuser)):
    return get_admin_settings()


@router.patch("/settings")
async def admin_settings_patch_route(payload: AdminSettingsPatchIn, admin=Depends(require_superuser)):
    return patch_admin_settings(admin, payload.values)


@router.get("/diagnostics/report")
async def diagnostics_route(_admin=Depends(require_superuser)):
    return get_diagnostics_report()


@router.get("/activity-feed")
async def activity_feed_route(limit: int = Query(default=200, ge=1, le=1000), _admin=Depends(require_admin)):
    return list_activity_feed(limit=limit)


@router.post("/ui-activity")
async def ui_activity_route(payload: AdminUiActivityIn, admin=Depends(require_admin)):
    return record_ui_activity(admin, payload.event, payload.meta)


@router.get("/server-log")
async def server_log_route(
    lines: int = Query(default=200, ge=1, le=1000),
    _admin=Depends(require_superuser),
):
    return get_server_log_tail(lines=lines)


@router.get("/secrets")
async def install_secrets_route(_admin=Depends(require_superuser)):
    return get_install_secrets()


@router.post("/secrets/reveal")
async def reveal_secret_route(payload: AdminRevealSecretIn, admin=Depends(require_superuser)):
    try:
        return reveal_secret(admin, payload.key)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
