package com.xindazhou.framework.apilog.core.service.impl;

import com.xindazhou.framework.apilog.core.service.ApiAccessLogStorageStrategy;
import com.xindazhou.framework.common.biz.infra.logger.dto.ApiAccessLogCreateReqDTO;
import com.xindazhou.framework.common.util.json.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 只记录日志文件存储策略
 *
 * @author xdz
 */
@Slf4j
@RequiredArgsConstructor
public class LogOnlyStorageStrategy implements ApiAccessLogStorageStrategy {

    private final String applicationName;
    private final String logFilePath;

    @Override
    public void save(ApiAccessLogCreateReqDTO createDTO) {
        try {
            // 构建 JSON 日志对象
            Map<String, Object> logMap = new HashMap<>();
            logMap.put("type", "api-access-log");
            logMap.put("timestamp", createDTO.getBeginTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            logMap.put("traceId", createDTO.getTraceId());
            logMap.put("applicationName", applicationName);
            logMap.put("requestMethod", createDTO.getRequestMethod());
            logMap.put("requestUrl", createDTO.getRequestUrl());
            logMap.put("requestParams", createDTO.getRequestParams());
            logMap.put("userId", createDTO.getUserId());
            logMap.put("userType", createDTO.getUserType());
            logMap.put("userIp", createDTO.getUserIp());
            logMap.put("userAgent", createDTO.getUserAgent());
            logMap.put("operateModule", createDTO.getOperateModule());
            logMap.put("operateName", createDTO.getOperateName());
            logMap.put("operateType", createDTO.getOperateType());
            logMap.put("beginTime", createDTO.getBeginTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            logMap.put("endTime", createDTO.getEndTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            logMap.put("duration", createDTO.getDuration());
            logMap.put("resultCode", createDTO.getResultCode());
            logMap.put("resultMsg", createDTO.getResultMsg());

            // 转换为 JSON 字符串
            String jsonLog = JsonUtils.toJsonString(logMap);

            // 写入日志文件
            writeToFile(jsonLog);
        } catch (Throwable th) {
            log.error("[save][保存 API 访问日志到文件失败，log({})]", createDTO, th);
        }
    }

    private void writeToFile(String jsonLog) throws IOException {
        Path path = Paths.get(logFilePath);
        Path parent = path.getParent();
        if (parent != null && !Files.exists(parent)) {
            Files.createDirectories(parent);
        }

        try (FileWriter writer = new FileWriter(logFilePath, true)) {
            writer.write(jsonLog);
            writer.write(System.lineSeparator());
            writer.flush();
        }
    }

}

