from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from datetime import datetime
from ..models.audit_log import AuditLog
from ..config.logging_config import get_logger
logger = get_logger(__name__)

class AuditService:

    @staticmethod
    async def log_action(db: Session, action: str, resource_type: str, user_id: Optional[int]=None, resource_id: Optional[int]=None, ip_address: Optional[str]=None, user_agent: Optional[str]=None, request_id: Optional[str]=None, details: Optional[Dict[str, Any]]=None, status: str='success', error_message: Optional[str]=None):
        try:
            audit_log = AuditLog(user_id=user_id, action=action, resource_type=resource_type, resource_id=resource_id, ip_address=ip_address, user_agent=user_agent, request_id=request_id, details=details, status=status, error_message=error_message)
            db.add(audit_log)
            db.commit()
            logger.info(f'Audit log created: {action} on {resource_type}', extra={'action': action, 'resource_type': resource_type, 'resource_id': resource_id, 'user_id': user_id, 'status': status, 'request_id': request_id})
        except Exception as e:
            logger.error(f'Failed to create audit log: {str(e)}', exc_info=True)
            db.rollback()
audit_service = AuditService()