# repositories/audit_log_repository.py
import json
from db import get_connection

def create_audit_log(
    user_id=None,
    username=None,
    role=None,
    action="",
    entity_type=None,
    entity_id=None,
    match_id=None,
    session_token=None,
    ip_address=None,
    user_agent=None,
    details=None,
):
    conn = get_connection()
    try:
        with conn:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    INSERT INTO audit_logs (
                        user_id, username, role, action, entity_type, entity_id,
                        match_id, session_token, ip_address, user_agent, details
                    )
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb)
                    """,
                    (
                        user_id,
                        username,
                        role,
                        action,
                        entity_type,
                        entity_id,
                        match_id,
                        session_token,
                        ip_address,
                        user_agent,
                        json.dumps(details or {}, ensure_ascii=False),
                    ),
                )
    finally:
        conn.close()