package handlers

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

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

// HandleVersionsGet godoc
// @Summary Returns versions for VIN.
// @Description Returns versions for VIN at a point in time
// @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"
// @Param timestamp query string false "at date (2023-01-13)"
// @Success 200 {object} map[string]string
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 404 {object} common.JSONError "Not Found"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicle/{vin}/version [get]
func HandleVersionsGet(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	qs := r.URL.Query()
	req := getVersionsRequest{
		VIN:       params.ByName("vin"),
		Timestamp: qs.Get("timestamp"),
	}
	err := validator.ValidateStruct(req)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	result, err := services.GetDB().GetCarVersionsLog().GetCarVersions(req.VIN, req.GetTimestamp())
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	utils.RespJSON(w, http.StatusOK, result)
}

type getVersionsRequest struct {
	VIN       string `validate:"vin,required"`
	Timestamp string `validate:"yyyymmdddate"`
}

func (g *getVersionsRequest) GetTimestamp() time.Time {
	if len(g.Timestamp) > 0 {
		date, err := time.Parse("2006-01-02", g.Timestamp)
		if err == nil {
			return date.Add(time.Second * 86399)
		}
		logger.Warn().AnErr("getVersionsRequest.GetTimestamp", err).Send()
	}

	return time.Now()
}
