package com.madeu.crm.settings.log.svc;

import com.madeu.constants.Constants;
import com.madeu.crm.settings.log.dto.LogHistoryDTO;
import com.madeu.crm.settings.log.mapper.LogHistoryMapper;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Slf4j
@Service("LogHistoryViewService")
public class LogHistoryService {

    @Autowired
    private HttpSession session;

    @Autowired
    private LogHistoryMapper logHistoryMapper;

    @Autowired
    private MessageSource messageSource;

    private String msg(String code) {
        return messageSource.getMessage(code, null, Locale.getDefault());
    }

    public LogHistoryDTO getLogHistoryList(LogHistoryDTO dto) {
        try {
            // 로그 히스토리는 시스템 관리 기능 → 로그인 여부만 체크
            String loginMemberId = (String) session.getAttribute("loginMemberId");
            if (loginMemberId != null && !loginMemberId.isEmpty() && !"null".equals(loginMemberId)) {
                dto.setUseYn("Y");

                List<LogHistoryDTO> countList = logHistoryMapper.selectTotalLogHistoryCount(dto);
                int total = countList.get(0).getTotalCount();

                dto.setTotalCount(total);
                if (total > 0) {
                    dto.setRows(logHistoryMapper.selectListLogHistory(dto));
                } else {
                    dto.setRows(new ArrayList<>());
                }
                dto.setMsgCode(Constants.OK);
                dto.setSuccess("true");
            } else {
                dto.setMsgCode(Constants.FAIL);
                dto.setMsgDesc(msg("auth.error.select"));
            }
        } catch (Exception e) {
            log.error("Error in getLogHistoryList", e);
            dto.setMsgCode(Constants.FAIL);
            dto.setMsgDesc(msg("error.select"));
        }
        return dto;
    }
}
