package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	fv "github.com/fiskerinc/cloud-services/pkg/flashpackversion"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/julienschmidt/httprouter"
)

// HandleFlashpackVersionGetInfo godoc
// @Summary Get flashpack version info for a car
// @Description Get flashpack version info (version number, ECUs to be updated for next version) for a car
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin path string true "VIN"
// @Success 200 {object} common.JSONDBQueryResult "Get flashpack version info result"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /flashpack_version_info/{vin} [get]
func HandleFlashpackVersionInfoGet(w http.ResponseWriter, r *http.Request) {
	vin := httprouter.ParamsFromContext(r.Context()).ByName("vin")
	err := validator.ValidateField(vin, "vin")
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	cars := services.GetDB().GetCars()

	car, err := cars.SelectByVIN(vin)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	nextFlashpackVersion, err := cars.GetNextFlashpackVersion(car.Model, car.Trim, car.Flashpack)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	if nextFlashpackVersion != nil {
		ecusNeededForNextFlashpack, err := fv.FindCarECUsToUpdateForNextFlashpackNumber(cars, *car, nextFlashpackVersion.Flashpack)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
			return
		}

		// Sort by ECU name in alphabetical order
		sort.Slice(ecusNeededForNextFlashpack, func(i, j int) bool {
			return ecusNeededForNextFlashpack[i].CarECUName < ecusNeededForNextFlashpack[j].CarECUName
		})

		utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
			Data: common.CarFlashpackVersionInfoResponse{
				Flashpack:     car.Flashpack,
				NextFlashpack: nextFlashpackVersion.Flashpack,
				ECUVersions:   ecusNeededForNextFlashpack,
			},
		})
	} else {
		utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
			Data: common.CarFlashpackVersionInfoResponse{
				Flashpack: car.Flashpack,
			},
		})
	}
}
