"""
Admin Audit Logging Service
Tracks all admin actions for compliance and debugging.
"""

from typing import Dict, Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from datetime import datetime
import logging

from ..models import AdminAction, User

log = logging.getLogger(__name__)

# Dev/mock user IDs that won't exist in the users table
DEV_USER_IDS = {"dev-admin", "test-admin", "mock-admin"}


async def log_admin_action(
    admin_user_id: str,
    admin_email: str,
    action: str,
    db: AsyncSession,
    target_account_id: Optional[str] = None,
    details: Optional[Dict[str, Any]] = None,
) -> None:
    """
    Log an admin action to the audit trail.

    Args:
        admin_user_id: ID of admin user performing the action
        admin_email: Email of admin user (for easy auditing)
        action: Action type (e.g., 'view_customer', 'adjust_credits')
        db: Database session
        target_account_id: Account affected by the action (if applicable)
        details: Additional details (before/after values, reason, etc.)

    Example:
        await log_admin_action(
            admin_user_id="admin_123",
            admin_email="mike@foundryops.io",
            action="adjust_credits",
            db=db,
            target_account_id="acct_456",
            details={
                "before": 100,
                "after": 200,
                "amount": 100,
                "reason": "Customer issue #123 - add 100 credits"
            }
        )
    """
    try:
        # Skip audit logging for dev/mock users that don't exist in the database
        # to avoid FK constraint violations
        if admin_user_id in DEV_USER_IDS:
            log.info(
                f"Admin action (dev mode, not persisted): {action} by {admin_email} "
                f"on account {target_account_id or 'N/A'}"
            )
            return

        # Verify user exists to avoid FK violation
        user_exists = await db.execute(
            select(User.id).where(User.id == admin_user_id).limit(1)
        )
        if not user_exists.scalar_one_or_none():
            log.warning(
                f"Admin user {admin_user_id} not found in users table, "
                f"skipping audit log for action: {action}"
            )
            return

        audit_entry = AdminAction(
            admin_user_id=admin_user_id,
            admin_email=admin_email,
            action=action,
            target_account_id=target_account_id,
            details=details,
            created_at=datetime.utcnow(),
        )

        db.add(audit_entry)
        await db.commit()

        log.info(
            f"Admin action logged: {action} by {admin_email} "
            f"on account {target_account_id or 'N/A'}"
        )

    except Exception as e:
        log.error(f"Failed to log admin action: {e}", exc_info=True)
        # Don't fail the request if audit logging fails
        # But do log it for investigation
        await db.rollback()
