/******************************************************************************
 * Copyright (c)  2021 PingCAP, Inc.                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");            *
 * you may not use this file except in compliance with the License.           *
 * You may obtain a copy of the License at                                    *
 *                                                                            *
 * http://www.apache.org/licenses/LICENSE-2.0                                 *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 ******************************************************************************/

package httpapi

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/errors"
	"github.com/tidbcloud/observability/pkg/common/message"
)

func Succeed(c *gin.Context, httpCode int, result interface{}) {
	messageResult := message.Result{
		Code:    0,
		Message: "",
		Data:    result,
	}

	if httpCode != http.StatusOK {
		newCtx := context.WithValue(c.Request.Context(), constants.RequestResultCtxKey, messageResult)
		c.Request = c.Request.WithContext(newCtx)
	}

	c.JSON(httpCode, messageResult)
}

func Fail(c *gin.Context, err error) {
	var (
		status int
		result message.Result
	)

	if e, ok := err.(errors.Error); ok {
		status = e.Code().GetHttpCode()
		result = message.Result{
			Code:    int(e.Code()),
			Message: err.Error(),
		}
	} else {
		status = errors.UnrecognizedError.GetHttpCode()
		result = message.Result{
			Code:    int(errors.UnrecognizedError),
			Message: err.Error(),
		}
	}

	c.JSON(status, result)
	newCtx := context.WithValue(c.Request.Context(), constants.RequestResultCtxKey, result)
	c.Request = c.Request.WithContext(newCtx)
}
