from django.contrib.auth.signals import user_logged_in, user_login_failed
from django.dispatch import receiver
from django.utils import timezone
from .context import TrackerContext
from .models import OperationLog
from .queue import enqueue_log
import logging

logger = logging.getLogger(__name__)

@receiver(user_logged_in)
def log_user_login(sender, request, user, **kwargs):
    trace_id = getattr(request, 'trace_id', TrackerContext.get_trace_id())
    enqueue_log(
        trace_id=trace_id,
        operation_type=OperationLog.OpType.AUTH,
        level='INFO',
        start_time=timezone.now(),
        user_id=str(user.pk),
        username=user.get_username(),
        details={'event': 'login', 'backend': str(sender)},
    )

from .utils import mask_sensitive_data

@receiver(user_login_failed)
def log_login_failed(sender, credentials, request, **kwargs):
    trace_id = getattr(request, 'trace_id', TrackerContext.get_trace_id())
    enqueue_log(
        trace_id=trace_id,
        operation_type=OperationLog.OpType.AUTH,
        level='WARNING',
        start_time=timezone.now(),
        details={'event': 'login_failed', 'credentials': mask_sensitive_data(credentials)}, 
    )
