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/utils/urlhelper"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleCarUpdatesGet godoc
// @Summary Search car updates
// @Description Get car updates filtered by id, car id, and update package id
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id query int false "CarUpdate id"
// @Param vin query string false "Car VIN"
// @Param manifest_id query int false "Update manifest id"
// @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"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.CarUpdate}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /carupdates [get]
func HandleCarUpdatesGet(w http.ResponseWriter, r *http.Request) {
	var total int
	cu := services.GetDB().GetCarUpdates()
	filter, err := parseCarsUpdateFilter(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 = "id DESC"
	}

	ups, err := cu.Select(filter, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

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

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

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

	filter := common.CarUpdate{
		ID:               urlhelper.GetQueryInt64(qs, "id"),
		VIN:              qs.Get("vin"),
		UpdateManifestID: urlhelper.GetQueryInt64(qs, "manifest_id"),
	}

	err := validator.ValidateNonRequired(filter)

	return &filter, err
}
