package handlers

import (
	"net/http"
	"regexp"
	"strconv"

	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"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"
)

var rxSWVersion = regexp.MustCompile(`\bsw_version\b`)

// HandleVehicleECUsGet godoc
// @Summary Get car ECUs
// @Description Returns ECUs for car
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin query string true "Car VIN"
// @Param search query string false "Text search"
// @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 unique query bool false "Get only latest ECU versions"
// @Success 200 {object} common.JSONDBQueryResult
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicleecus [get]
func HandleVehicleECUsGet(w http.ResponseWriter, r *http.Request) {
	var total int
	c := services.GetDB().GetCars()
	filter, err := parseCarECUsFilter(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	options, err := queries.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}
	updateCarECUsOptions(options)

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

	if options.Offset == 0 {
		total, err = c.GetCarECUsCount(filter)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
			return
		}
	}

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

func updateCarECUsOptions(options *queries.PageQueryOptions) {
	if options.Order == "" {
		options.Order = "ecu"
	} else {
		options.Order = rxSWVersion.ReplaceAllString(options.Order, "version")
	}
}

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

	unique, err := strconv.ParseBool(qs.Get("unique"))
	if err != nil {
		unique = false
	}

	filter := common.CarECUFilter{
		Search: qs.Get("search"),
		Unique: unique,
		VIN:    qs.Get("vin"),
	}

	err = validator.ValidateField(filter.VIN, "vin")

	return filter, err
}
