package webutil

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.rackspace.com/gorax/clients/coreAPI"
)

// Standard helper functions for use with gin

// GinDelete : Standardized response with both a "data" and "deleted" object
// Deprecated: Use in new location of github.rackspace.com/gorax/webutil
func GinDelete(c *gin.Context, data, deleted interface{}) {
	c.JSON(200, gin.H{
		"data":    data,
		"deleted": deleted,
	})
}

// GinError : Standardized error response
// Deprecated: Use in new location of github.rackspace.com/gorax/webutil
func GinError(c *gin.Context, code int, err error) {
	c.JSON(code, gin.H{
		"error": err.Error(),
	})
}

// GinData : Standarized response with a "data" object
// Deprecated: Use in new location of github.rackspace.com/gorax/webutil
func GinData(c *gin.Context, code int, data interface{}) {
	c.JSON(code, gin.H{
		"data": data,
	})
}

// GinDataRequest : Standardized response with "data" and "request" objects
// Deprecated: Use in new location of github.rackspace.com/gorax/webutil
func GinDataRequest(c *gin.Context, code int, data, request interface{}) {
	c.JSON(code, gin.H{
		"data":    data,
		"request": request,
	})
}

// GinCoreAuth : Verifies authtoken header is present and contains a valid core token by initializing a coreAPI client with that token and embeding it under "userCore"
// Deprecated: Use in new location of github.rackspace.com/gorax/webutil
func GinCoreAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.GetHeader("authtoken") == "" {
			_ = c.Error(errors.New("authtoken missing"))
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authtoken header missing"})
			return
		}
		// Verify token
		core, err := coreAPI.New(c.GetHeader("authtoken"))
		if err != nil {
			e := fmt.Errorf("error initializing coreAPI: %s", err.Error())
			_ = c.Error(e)
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": e.Error()})
			return
		}
		// Embed core in context, 'core' is for our netsec01 user so this is labelled 'userCore'
		c.Set("userCore", core)
	}
}
