/**
 * @Author: FTS Team
 * @Date: 2024-10-02
 * @Description: 统一响应处理
 */
package response

import (
	"net/http"

	"bsm/full/module/base/fts/internal/errors"
	"github.com/gin-gonic/gin"
)

// Response 统一响应结构
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
	TraceID string      `json:"trace_id,omitempty"`
}

// Success 成功响应
func Success(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    0,
		Message: "成功",
		Data:    data,
		TraceID: getTraceID(c),
	})
}

// SuccessWithMessage 带自定义消息的成功响应
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    0,
		Message: message,
		Data:    data,
		TraceID: getTraceID(c),
	})
}

// Error 错误响应
func Error(c *gin.Context, err error) {
	var businessErr *errors.BusinessError
	var httpStatus int
	var response Response

	// 检查是否为业务错误
	if bizErr, ok := err.(*errors.BusinessError); ok {
		businessErr = bizErr
		httpStatus = businessErr.HTTPStatus()
		response = Response{
			Code:    businessErr.Code,
			Message: businessErr.Message,
			TraceID: getTraceID(c),
		}
		// 如果有详细信息，添加到响应中
		if businessErr.Detail != "" {
			response.Data = map[string]string{"detail": businessErr.Detail}
		}
	} else {
		// 默认内部错误
		businessErr = errors.ErrInternalError
		httpStatus = http.StatusInternalServerError
		response = Response{
			Code:    businessErr.Code,
			Message: businessErr.Message,
			Data:    map[string]string{"detail": err.Error()},
			TraceID: getTraceID(c),
		}
	}

	c.JSON(httpStatus, response)
}

// ErrorWithCode 指定错误码的错误响应
func ErrorWithCode(c *gin.Context, code int, message string) {
	businessErr := errors.New(code, message)
	c.JSON(businessErr.HTTPStatus(), Response{
		Code:    code,
		Message: message,
		TraceID: getTraceID(c),
	})
}

// Forbidden 403响应
func Forbidden(c *gin.Context, message string) {
	if message == "" {
		message = "权限不足"
	}
	c.JSON(http.StatusForbidden, Response{
		Code:    errors.ErrCodeForbidden,
		Message: message,
		TraceID: getTraceID(c),
	})
}

// Unauthorized 401响应
func Unauthorized(c *gin.Context, message string) {
	if message == "" {
		message = "未授权访问"
	}
	c.JSON(http.StatusUnauthorized, Response{
		Code:    errors.ErrCodeUnauthorized,
		Message: message,
		TraceID: getTraceID(c),
	})
}

// NotFound 404响应
func NotFound(c *gin.Context, message string) {
	if message == "" {
		message = "资源不存在"
	}
	c.JSON(http.StatusNotFound, Response{
		Code:    errors.ErrCodeNotFound,
		Message: message,
		TraceID: getTraceID(c),
	})
}

// BadRequest 400响应
func BadRequest(c *gin.Context, message string) {
	if message == "" {
		message = "请求参数错误"
	}
	c.JSON(http.StatusBadRequest, Response{
		Code:    errors.ErrCodeInvalidParam,
		Message: message,
		TraceID: getTraceID(c),
	})
}

// getTraceID 从上下文中获取追踪ID
func getTraceID(c *gin.Context) string {
	if traceID := c.GetHeader("X-Trace-ID"); traceID != "" {
		return traceID
	}
	if traceID := c.GetString("trace_id"); traceID != "" {
		return traceID
	}
	return ""
}
