# app/modules/monitoring/routes/api/admin_audit.py
"""
Admin audit log endpoints.

Provides endpoints for:
- Viewing audit logs with filtering
- Tracking admin actions
- Generating audit reports
"""

import logging
from datetime import datetime

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.modules.monitoring.services.admin_audit_service import admin_audit_service
from app.modules.tenancy.schemas.admin import (
    AdminAuditLogFilters,
    AdminAuditLogListResponse,
    AdminAuditLogResponse,
)
from app.modules.tenancy.schemas.auth import UserContext

admin_audit_router = APIRouter(prefix="/audit")
logger = logging.getLogger(__name__)


@admin_audit_router.get("/logs", response_model=AdminAuditLogListResponse)
def get_audit_logs(
    admin_user_id: int | None = Query(None, description="Filter by admin user"),
    action: str | None = Query(None, description="Filter by action type"),
    target_type: str | None = Query(None, description="Filter by target type"),
    date_from: datetime | None = Query(None, description="Filter from date"),
    date_to: datetime | None = Query(None, description="Filter to date"),
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=1000, description="Maximum records to return"),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Get filtered admin audit logs.

    Returns paginated list of all admin actions with filtering options.
    Useful for compliance, security audits, and tracking admin activities.
    """
    filters = AdminAuditLogFilters(
        admin_user_id=admin_user_id,
        action=action,
        target_type=target_type,
        date_from=date_from,
        date_to=date_to,
        skip=skip,
        limit=limit,
    )

    logs = admin_audit_service.get_audit_logs(db, filters)
    total = admin_audit_service.get_audit_logs_count(db, filters)

    logger.info(f"Admin {current_admin.username} retrieved {len(logs)} audit logs")

    return AdminAuditLogListResponse(logs=logs, total=total, skip=skip, limit=limit)


@admin_audit_router.get("/logs/recent", response_model=list[AdminAuditLogResponse])
def get_recent_audit_logs(
    limit: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get recent audit logs (last 20 by default)."""
    filters = AdminAuditLogFilters(limit=limit)
    return admin_audit_service.get_audit_logs(db, filters)


@admin_audit_router.get("/logs/my-actions", response_model=list[AdminAuditLogResponse])
def get_my_actions(
    limit: int = Query(50, ge=1, le=100),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get audit logs for current admin's actions."""
    return admin_audit_service.get_recent_actions_by_admin(
        db=db, admin_user_id=current_admin.id, limit=limit
    )


@admin_audit_router.get("/logs/target/{target_type}/{target_id}")
def get_actions_by_target(
    target_type: str,
    target_id: str,
    limit: int = Query(50, ge=1, le=100),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """
    Get all actions performed on a specific target.

    Useful for tracking the history of a specific store, user, or entity.
    """
    return admin_audit_service.get_actions_by_target(
        db=db, target_type=target_type, target_id=target_id, limit=limit
    )
