import logging
from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession
from src.group_settings.models import LogEntry

logger = logging.getLogger(__name__)

async def log_action(
    session: AsyncSession,
    group_email: str,
    user_email: str,
    action: str,
    details: Optional[str] = None
):
    """
    Creates a new audit log entry in the database.
    """
    try:
        new_log = LogEntry(
            group_email=group_email,
            user_email=user_email,
            action=action,
            details=details
        )
        session.add(new_log)
        await session.commit()
    except Exception as e:
        # We don't want to fail the main request if logging fails, 
        # but we should definitely record the failure in the system logs.
        logger.error(f"CRITICAL: Failed to write audit log to DB: {e}")
        # Optionally, we could try to log to a file here as a fallback
