package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/go-pg/pg/v10/orm"
	"github.com/julienschmidt/httprouter"
	"github.com/pkg/errors"
)

// HandleSupplierDelete godoc
// @Summary Delete filter from vehicle
// @Description Delete filter from vehicle
// @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 "Email"
// @Success 200 {object} common.JSONMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /supplier/{email} [delete]
func HandleSupplierDelete(w http.ResponseWriter, r *http.Request) {
	supplierDelete.Handle(w, r)
}

var supplierDelete = controllers.NewDelete(&supplierDeleteHelper{})

type supplierDeleteHelper struct {
	controllers.HandleDelete
}

func (h *supplierDeleteHelper) ParseDeleteQueryParams(r *http.Request) interface{} {
	req := common.SupplierAccount{}
	params := httprouter.ParamsFromContext(r.Context())

	req.Email = params.ByName("email")

	return &req
}

func (h *supplierDeleteHelper) ValidatePK(model interface{}) error {
	req, ok := model.(*common.SupplierAccount)
	if !ok {
		return errors.New("invalid request")
	}

	if req.Email != "" {
		return nil
	}

	err := validator.ValidateStruct(req)
	if err != nil {
		return errors.New("email required")
	}

	return nil
}

func (h *supplierDeleteHelper) QueryDelete(model interface{}) (orm.Result, error) {
	return services.GetDB().GetSupplierAccounts().Delete(model.(*common.SupplierAccount))
}
