package com.ycwl.basic.stats.controller;

import com.ycwl.basic.annotation.IgnoreToken;
import com.ycwl.basic.stats.dto.AddTraceReq;
import com.ycwl.basic.stats.service.StatsService;
import com.ycwl.basic.stats.util.StatsUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/trace/v1")
public class TraceController {
    @Autowired
    private StatsService statsService;
    @IgnoreToken
    @PostMapping("/start")
    public void startTrace(HttpServletRequest request, HttpServletResponse response) {
        String traceId = request.getHeader("traceId");
        if (traceId == null || traceId.isEmpty()) {
            traceId = StatsUtil.createUuid();
            response.setHeader("Set-TraceId", traceId);
        }
        statsService.addStats(traceId, null);
    }

    @IgnoreToken
    @PostMapping("/add")
    public void addTrace(HttpServletRequest request, HttpServletResponse response, @RequestBody AddTraceReq req) {
        String traceId = request.getHeader("traceId");
        if (traceId == null || traceId.isEmpty()) {
            traceId = StatsUtil.createUuid();
            response.setHeader("Set-TraceId", traceId);
        }
        if (StringUtils.isEmpty(req.getParams())) {
            req.setParams(null);
        }
        statsService.addRecord(traceId, req.getAction(), req.getIdentifier(), req.getParams());
    }
}
