# /opt/docker/dev/service_finder/backend/app/db/middleware.py
from fastapi import Request
from app.db.session import AsyncSessionLocal
from app.models import OperationalLog # JAVÍTVA: Az új modell
from sqlalchemy import text

async def audit_log_middleware(request: Request, call_next):
    # Itt a config_service-t is aszinkron módon kell hívni, ha szükséges
    response = await call_next(request)
    
    if request.method != 'GET': 
        try:
            user_id = getattr(request.state, 'user_id', None)
            async with AsyncSessionLocal() as db:
                log = OperationalLog(
                    user_id=user_id,
                    action=f"API_CALL_{request.method}",
                    resource_type="ENDPOINT",
                    resource_id=str(request.url.path),
                    details={"ip": request.client.host, "method": request.method}
                )
                db.add(log)
                await db.commit()
        except Exception:
            pass # A naplózás nem akaszthatja meg a folyamatot
            
    return response