package handlers

import (
	"net/http"

	"otaupdate/services"

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

// HandleIssuesGet godoc
// @Summary Search Issues
// @Description Returns all Issues
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.Issue}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /issues [get]
func HandleIssuesGet(w http.ResponseWriter, r *http.Request) {
	var total int
	c := services.GetDB().GetIssues()

	filter, err := parseIssuesFilter(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

	issues, err := c.Search(filter, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	total, err = c.Count()
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

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

func parseIssuesFilter(r *http.Request) (*common.IssueSearch, error) {
	qs := r.URL.Query()

	filter := common.IssueSearch{
		Search: qs.Get("search"),
	}

	err := validator.ValidateNonRequired(filter)

	return &filter, err
}
