package com.zioinfo.mall.admin;

import com.zioinfo.mall.admin.dto.AuditLog;
import com.zioinfo.mall.admin.mapper.AuditLogMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 감사 로그 서비스.
 *
 * <p>관리자/주문/결제 등 주요 작업 시 호출하여 mall_audit_log 에 기록한다.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuditService {

    private final AuditLogMapper mapper;

    public void log(String action, String target, String detail) {
        log(currentActor(), action, target, detail);
    }

    public void log(String actor, String action, String target, String detail) {
        AuditLog entry = new AuditLog();
        entry.setActor(actor);
        entry.setAction(action);
        entry.setTarget(target);
        entry.setDetail(detail);
        try {
            mapper.insert(entry);
        } catch (Exception e) {
            log.warn("감사 로그 기록 실패(무시): {}", e.getMessage());
        }
    }

    public List<AuditLog> find(String action, String actor, int limit) {
        int safeLimit = (limit <= 0 || limit > 1000) ? 100 : limit;
        return mapper.find(action, actor, safeLimit);
    }

    public static String currentActor() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.getName() != null && !auth.getName().isBlank()) {
            return auth.getName();
        }
        return "system";
    }
}
