package handlers

import (
	"fmt"
	"net/http"
	"strconv"

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

	"otaupdate/services"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleCarUpdatesLog godoc
// @Summary Gets log of car update statuses
// @Description Returns array of car update statuses
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param carupdateid query int true "car update id"
// @Success 200 {object} CarUpdateStatuses "Car update statuses"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /carupdateslog [get]
func HandleCarUpdatesLog(w http.ResponseWriter, r *http.Request) {
	var total int
	carupdateID, err := validateCarUpdatesLog(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"
	}

	cu := services.GetDB().GetCarUpdates()
	statuses, err := cu.GetUpdateStatuses(carupdateID, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	if options.Offset == 0 {
		total, err = cu.CountUpdateStatuses(carupdateID)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
			return
		}
	}

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

func validateCarUpdatesLog(r *http.Request) (int64, error) {
	qs := r.URL.Query()
	qsID := qs.Get("carupdateid")

	if qsID == "" {
		return 0, fmt.Errorf("car update id required")
	}

	id, err := strconv.ParseInt(qsID, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid id %s", qsID)
	}
	return id, nil
}
