package gc.mda.kcg.auth;

import gc.mda.kcg.audit.AuditLog;
import gc.mda.kcg.audit.AuditLogRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 로그인 이력 + 감사 로그 기록 전용 컴포넌트.
 * REQUIRES_NEW 트랜잭션으로 분리 → 인증 실패로 외부 트랜잭션이 롤백되어도 기록 보존.
 */
@Component
@RequiredArgsConstructor
public class LoginAuditWriter {

    private final LoginHistoryRepository loginHistoryRepository;
    private final AuditLogRepository auditLogRepository;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void recordSuccess(UUID userId, String userAcnt, String ipAddress, String userAgent) {
        loginHistoryRepository.save(LoginHistory.builder()
                .userId(userId)
                .userAcnt(userAcnt)
                .loginIp(ipAddress)
                .userAgent(userAgent)
                .result("SUCCESS")
                .authProvider("PASSWORD")
                .build());

        auditLogRepository.save(AuditLog.builder()
                .userId(userId)
                .userAcnt(userAcnt)
                .actionCd("LOGIN")
                .resourceType("SYSTEM")
                .resourceId("auth")
                .ipAddress(ipAddress)
                .result("SUCCESS")
                .build());
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void recordFailure(String userAcnt, String ipAddress, String userAgent, String failReason) {
        String result = failReason != null && failReason.startsWith("MAX_FAIL") ? "LOCKED" : "FAILED";

        loginHistoryRepository.save(LoginHistory.builder()
                .userAcnt(userAcnt)
                .loginIp(ipAddress)
                .userAgent(userAgent)
                .result(result)
                .failReason(failReason)
                .authProvider("PASSWORD")
                .build());

        auditLogRepository.save(AuditLog.builder()
                .userAcnt(userAcnt)
                .actionCd("LOGIN")
                .resourceType("SYSTEM")
                .resourceId("auth")
                .ipAddress(ipAddress)
                .result("FAILED")
                .failReason(failReason)
                .build());
    }
}
