package tech.easyflow.ai.service.impl;

import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tech.easyflow.ai.service.KnowledgeShareAuditService;
import tech.easyflow.common.util.RequestUtil;
import tech.easyflow.system.entity.SysLog;
import tech.easyflow.system.service.SysLogService;

import javax.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;

/**
 * 知识库分享审计服务实现。
 */
@Service
public class KnowledgeShareAuditServiceImpl implements KnowledgeShareAuditService {

    @Resource
    private SysLogService sysLogService;

    @Override
    public void log(BigInteger accountId, String actionName, String actionType, String actionUrl, Map<String, Object> detail) {
        SysLog log = new SysLog();
        log.setAccountId(accountId);
        log.setActionName(actionName);
        log.setActionType(actionType);
        log.setActionUrl(actionUrl);
        log.setActionBody(detail == null ? null : JSON.toJSONString(detail));
        log.setCreated(new Date());
        log.setStatus(0);
        ServletRequestAttributes attributes =
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            log.setActionIp(RequestUtil.getIpAddress(request));
            log.setActionParams(request.getQueryString());
        }
        sysLogService.save(log);
    }
}

