package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
	"github.com/fiskerinc/cloud-services/pkg/validator"
)

var apiDeleteToken string = envtool.GetEnv("MIGRATE_DELETE_TOKEN", "")

// HandleFlashpackVersionDelete godoc
// @Summary Delete a flashpack version
// @Description Delete a flashpack version
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param data body common.CarFlashpackVersionRequest true "Flashpack version"
// @Success 200 {object} common.JSONDBQueryResult "Deleted flashpack ecu mapping result"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /flashpack_version [delete]
func HandleFlashpackVersionDelete(w http.ResponseWriter, r *http.Request) {
	var req common.CarFlashpackVersionRequest

	err := httphandlers.ParseRequest(r, &req)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	err = services.GetDB().GetCars().DeleteFlashpackVersion(req.CarModel, req.CarTrim, req.CarYear, req.Flashpack)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	// Also delete in other environments, as required
	for _, targetURL := range targetURLS {
		if !validator.ValidateURL(targetURL) || apiDeleteToken == "" {
			break // No URL in MANIFEST_MIGRATE_URLS
		}

		otaService := services.NewOtaService(targetURL, apiDeleteToken)

		resp, err := otaService.FlashpackVersionDelete(req)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
			return
		}

		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			utils.ForwardResponse(w, resp)
		}
	}

	utils.RespJSON(w, http.StatusOK, common.JSONMessage{
		Message: "Deleted",
	})
}
