package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/common/authproviders"
	orm "github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/utils/urlhelper"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleUpdateManifestsGet godoc
// @Summary Search update manifests
// @Description Get update manifests filtered by id, name, version, description
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param search query string false "Text search"
// @Param id query string false "Update manifest id"
// @Param name query string false "Update manifest name"
// @Param version query string false "Update manifest version"
// @Param desc query string false "Update manifest description"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Param order query string false "Sort on column with asc or desc"
// @Param manifest_type query int false "Manifest type (1=software, 2=configuration)"
// @Param active query boolean false "Filter by activate or inactive manifests"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.UpdateManifest}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifests [get]
func HandleUpdateManifestsGet(w http.ResponseWriter, r *http.Request) {
	var total int
	filter, err := parseUpdateManifestFilter(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	if provider := utils.AUTHGetProviderFromRequest(r); provider == authproviders.Magna || provider == authproviders.FiskerQA {
		filter.ManifestType = common.MagnaManifestUpdateType
	}

	options, err := orm.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}
	if options.Order == "" {
		options.Order = "created_at DESC"
	}

	um := services.GetDB().GetUpdateManifests()
	ums, err := um.Search(filter, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	if options.Offset == 0 && filter.ID == 0 {
		total, err = um.SearchCount(filter)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
			return
		}
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
		Data:  ums,
		Total: total,
	})
}

func parseUpdateManifestFilter(r *http.Request) (common.UpdateManifestSearch, error) {
	qs := r.URL.Query()
	filter := common.UpdateManifestSearch{
		Search: qs.Get("search"),
		UpdateManifest: common.UpdateManifest{
			ID:           urlhelper.GetQueryInt64(qs, "id"),
			Name:         qs.Get("name"),
			Version:      qs.Get("version"),
			Description:  qs.Get("desc"),
			ManifestType: common.UpdateManifestType(urlhelper.GetQueryInt(qs, "manifest_type")),
		},
	}

	active, ok := urlhelper.GetQueryBool(qs, "active")
	if ok {
		filter.UpdateManifest.Active = &active
	}

	err := validator.ValidateNonRequired(filter)

	return filter, err
}
