package com.zioinfo.mes.admin;

import com.zioinfo.mes.admin.dto.AuditLog;
import com.zioinfo.mes.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;

/**
 * 감사 로그 서비스 — 작업지시 전이·실적·검사 판정·관리자 작업 등 주요 변경을 mes_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) {
        try {
            AuditLog entry = new AuditLog();
            entry.setActor(actor);
            entry.setAction(action);
            entry.setTarget(target);
            entry.setDetail(detail);
            mapper.insert(entry);
        } catch (Exception e) {
            log.warn("감사 로그 기록 실패 [{}]: {}", action, 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);
    }

    /** SecurityContext 의 JWT subject(username)를 추출. 없으면 system. */
    public static String currentActor() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.getName() != null && !auth.getName().isBlank()) {
            return auth.getName();
        }
        return "system";
    }
}
