from fastapi import Request
from app.db.session import SessionLocal
from app.services.config_service import config
from sqlalchemy import text
import json

async def audit_log_middleware(request: Request, call_next):
    logging_enabled = await config.get_setting('audit_log_enabled', default=True)
    
    response = await call_next(request)
    
    if logging_enabled and request.method != 'GET': # GET-et általában nem naplózunk a zaj miatt, de állítható
        try:
            user_id = getattr(request.state, 'user_id', None) # Ha már be van lépve
            
            async with SessionLocal() as db:
                await db.execute(text("""
                    INSERT INTO data.audit_logs (user_id, action, endpoint, method, ip_address) 
                    VALUES (:u, :a, :e, :m, :ip)
                """), {
                    'u': user_id,
                    'a': f'API_CALL_{request.method}',
                    'e': str(request.url.path),
                    'm': request.method,
                    'ip': request.client.host
                })
                await db.commit()
        except Exception:
            pass # A naplózás hibája nem akaszthatja meg a kiszolgálást
            
    return response
