package handlers

import (
	"net/http"
	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/go-pg/pg/v10/orm"
	"github.com/gorilla/schema"
)

// APITokenDelete godoc
// @Summary Delete API token
// @Description Delete API token. Requires delete permissions
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param token query string true "API token"
// @Success 200 {object} common.JSONMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /apitoken [delete]
func HandleAPITokenDelete(w http.ResponseWriter, r *http.Request) {
	apiTokenDelete.Handle(w, r)
}

var apiTokenDelete = controllers.NewDelete(&apiTokenDeleteHelper{})

type apiTokenDeleteHelper struct {
	APITokensHelper
}

func (h *apiTokenDeleteHelper) ParseDeleteQueryParams(r *http.Request) interface{} {
	req := common.APIToken{}
	decoder := schema.NewDecoder()

	decoder.SetAliasTag("json")
	decoder.Decode(&req, r.URL.Query())

	return &req
}

func (h *apiTokenDeleteHelper) QueryDelete(model interface{}) (orm.Result, error) {
	result := model.(*common.APIToken)
	return services.GetDB().GetAPITokens().Delete(result.Token)
}

type APITokenDeleteRequest struct {
	Token string `json:"token"`
}
