package com.mvrent.carrental.config;

import com.mvrent.carrental.service.AuditService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

/** Records login successes and failures in the audit trail. */
@Component
@RequiredArgsConstructor
public class AuthEventListener {

    private final AuditService auditService;

    @EventListener
    public void onSuccess(AuthenticationSuccessEvent event) {
        auditService.logAuth("LOGIN_SUCCESS", event.getAuthentication().getName());
    }

    @EventListener
    public void onFailure(AbstractAuthenticationFailureEvent event) {
        Object principal = event.getAuthentication() != null ? event.getAuthentication().getPrincipal() : null;
        auditService.logAuth("LOGIN_FAILURE", principal != null ? String.valueOf(principal) : "unknown");
    }
}
