from typing import Annotated
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func

from app.core.database import get_db
from app.models.user import User
from app.models.subscription import Subscription
from app.models.tree import Tree
from app.models.audit_log import AuditLog
from app.schemas.admin import DashboardMetrics, ActivityEntry
from app.api.deps import require_admin

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


@router.get("/metrics", response_model=DashboardMetrics)
async def get_dashboard_metrics(
    db: Annotated[AsyncSession, Depends(get_db)],
    current_user: Annotated[User, Depends(require_admin)],
):
    """Get platform overview metrics."""
    total_users = await db.scalar(select(func.count()).select_from(User)) or 0
    active_subs = await db.scalar(
        select(func.count()).select_from(Subscription).where(
            Subscription.status.in_(["active", "trialing"])
        )
    ) or 0
    paid_accounts = await db.scalar(
        select(func.count()).select_from(Subscription).where(
            Subscription.plan.in_(["pro", "team"])
        )
    ) or 0
    total_trees = await db.scalar(
        select(func.count()).select_from(Tree).where(Tree.deleted_at.is_(None))
    ) or 0

    return DashboardMetrics(
        total_users=total_users,
        active_subscriptions=active_subs,
        paid_accounts=paid_accounts,
        total_trees=total_trees,
    )


@router.get("/activity", response_model=list[ActivityEntry])
async def get_dashboard_activity(
    db: Annotated[AsyncSession, Depends(get_db)],
    current_user: Annotated[User, Depends(require_admin)],
):
    """Get recent audit log entries for activity feed."""
    query = (
        select(
            AuditLog.id,
            AuditLog.action,
            AuditLog.resource_type,
            AuditLog.resource_id,
            AuditLog.details,
            AuditLog.ip_address,
            AuditLog.created_at,
            User.email.label("user_email"),
        )
        .outerjoin(User, AuditLog.user_id == User.id)
        .order_by(AuditLog.created_at.desc())
        .limit(10)
    )
    result = await db.execute(query)
    rows = result.all()

    return [
        ActivityEntry(
            id=row.id,
            user_email=row.user_email,
            action=row.action,
            resource_type=row.resource_type,
            resource_id=row.resource_id,
            details=row.details,
            ip_address=row.ip_address,
            created_at=row.created_at,
        )
        for row in rows
    ]
