package com.adx.tracking.httpapi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.util.Map;

/**
 * 全局异常处理器：对齐 Go 的 respondError(c, status, err) 返回格式 {"error": "message"}。
 * Go 中所有错误统一返回 {"error": "..."} + 明确的 HTTP 状态码，
 * Spring 默认返回 {"timestamp":..., "status":..., "error":..., "message":...} 格式不一致。
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * ResponseStatusException（手动抛出的带状态码的异常）。
     * 对应 Go: respondError(c, specificStatus, err)
     */
    @ExceptionHandler(ResponseStatusException.class)
    public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
        String reason = ex.getReason() != null ? ex.getReason() : ex.getMessage();
        return ResponseEntity.status(ex.getStatusCode())
                .body(Map.of("error", reason));
    }

    /**
     * IllegalArgumentException（参数校验失败）。
     * 对应 Go: respondError(c, http.StatusBadRequest, err)
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, String>> handleBadRequest(IllegalArgumentException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Map.of("error", ex.getMessage()));
    }

    /**
     * IOException / InterruptedException（外部服务调用失败）。
     * 对应 Go: respondError(c, http.StatusBadGateway, err)
     */
    @ExceptionHandler({IOException.class, InterruptedException.class})
    public ResponseEntity<Map<String, String>> handleBadGateway(Exception ex) {
        log.error("External service error: {}", ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                .body(Map.of("error", ex.getMessage()));
    }

    /**
     * 兜底：所有未预期异常。
     * 对应 Go: respondError(c, http.StatusBadGateway, err)
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, String>> handleGeneral(Exception ex) {
        log.error("Unhandled exception: {}", ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                .body(Map.of("error", ex.getMessage() != null ? ex.getMessage() : "internal error"));
    }
}
