package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/gorilla/schema"
)

// HandleSuppliersGetList godoc
// @Summary Search supplier accounts
// @Description Get supplier accounts filtered by id or email
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id query string false "Supplier id"
// @Param email query string false "Supplier email"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.SupplierAccount}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /suppliers [get]
func HandleSuppliersGetList(w http.ResponseWriter, r *http.Request) {
	suppliersGetList.Handle(w, r)
}

var suppliersGetList = controllers.NewGetList(&suppliersGetListHelper{})

type suppliersGetListHelper struct {
	SuppliersHelper
}

func (h *suppliersGetListHelper) ParseGetListQueryParams(r *http.Request) interface{} {
	schema := schema.NewDecoder()
	filter := common.SupplierAccount{}

	schema.SetAliasTag("json")
	schema.Decode(&filter, r.URL.Query())

	return &filter
}

func (h *suppliersGetListHelper) QueryCount(filter interface{}) (int, error) {
	return services.GetDB().GetSupplierAccounts().Count(filter.(*common.SupplierAccount))
}

func (h *suppliersGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	return services.GetDB().GetSupplierAccounts().Select(filter.(*common.SupplierAccount), options)
}

type SuppliersHelper struct {
	controllers.HelperBase
}

func (h *SuppliersHelper) NewModel() interface{} {
	return &common.SupplierAccount{}
}

func (h *SuppliersHelper) HasPK(filter interface{}) bool {
	result := filter.(*common.SupplierAccount)
	return result.Email != ""
}

func (h *SuppliersHelper) ValidatePK(model interface{}) error {
	result := model.(*common.SupplierAccount)

	err := validator.ValidateField(result.Email, "required,email")
	if err != nil {
		return controllers.ErrorPKRequired
	}

	return nil
}
