package com.madeu.common.service;

import com.madeu.service.web.webloghistory.WebLogHistoryService;
import com.madeu.util.RequestLogUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class LogHistoryService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private WebLogHistoryService webLogHistoryService;

    /**
     * 로그 히스토리 저장 (공통)
     *
     * @param funcName    기능명 (예: "권한그룹 수정")
     * @param serviceName 서비스명 (예: "권한그룹 수정")
     * @param requestObj  요청 파라미터 (DTO 또는 HashMap)
     * @param responseObj 응답 데이터 (DTO 또는 HashMap)
     * @param errorMsg    에러 메시지 (없으면 null 또는 빈 문자열)
     */
    public void save(String funcName, String serviceName,
            Object requestObj, Object responseObj, String errorMsg) {
        try {
            String uri = request.getRequestURI();
            String func = uri.substring(uri.lastIndexOf("/") + 1).replace(".do", "");
            String[] paths = uri.split("/");
            String servicePath = paths.length > 1 ? paths[1] + "Service" : "";
            String loginMemberId = (String) session.getAttribute("loginMemberId");

            HashMap<String, Object> visitLogParamMap = RequestLogUtil.getVisitLogParameterMap(request);
            HashMap<String, Object> insertMap = new HashMap<>();
            insertMap.put("url", uri);
            insertMap.put("func", func);
            insertMap.put("funcName", funcName);
            insertMap.put("service", servicePath);
            insertMap.put("serviceName", serviceName);
            insertMap.put("requestValue", String.valueOf(requestObj));
            insertMap.put("responseValue", String.valueOf(responseObj));
            insertMap.put("resultCode", (errorMsg == null || errorMsg.isEmpty()) ? "SUCCESS" : "ERROR");
            insertMap.put("resultMsg", errorMsg != null ? errorMsg : "");
            insertMap.put("muMemberId", loginMemberId);

            if (responseObj instanceof Map) {
                insertMap.put("tId", ((Map<?, ?>) responseObj).get("tId"));
            }

            webLogHistoryService.insertLogHistory(insertMap, visitLogParamMap);
        } catch (Exception e) {
            log.error("로그 히스토리 저장 실패", e);
        }
    }
}
