package handlers

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

	"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"
)

// HandleSupplierActivate godoc
// @Summary Activate supplier account
// @Description Updates the activated date for the supplier
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param email path string true "Supplier email address"
// @Success 200 {object} ApproveResponse
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /supplier/activate/{email} [post]
func HandleSupplierActivate(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	email := params.ByName("email")

	err := validator.ValidateField(email, "required,email")
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	_, err = services.GetDB().GetSupplierAccounts().Approve(email)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	utils.RespJSON(w, http.StatusOK, ApproveResponse{
		Activate: time.Now(),
	})
}

type ApproveResponse struct {
	Activate time.Time `json:"activate"`
}
