package handlers

import (
	"encoding/json"
	"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"
)

// HandleSupplierUpdate godoc
// @Summary Approve supplier account
// @Description Approve supplier account with Azure AD oid
// @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"
// @Param account body common.SupplierAccount true "Supplier account data"
// @Success 200 {object} common.SupplierAccount
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /supplier/{email} [put]
func HandleSupplierUpdate(w http.ResponseWriter, r *http.Request) {
	supplierUpdate.Handle(w, r)
}

var supplierUpdate = controllers.NewUpdate(&supplierUpdateHelper{})

type supplierUpdateHelper struct {
	SuppliersHelper
}

func (h *supplierUpdateHelper) ParseRequest(r *http.Request, data interface{}) error {
	model, ok := data.(*common.SupplierAccount)
	if !ok {
		return errors.New("model is not SupplierAccount")
	}

	err := json.NewDecoder(r.Body).Decode(data)
	if err != nil {
		return err
	}

	params := httprouter.ParamsFromContext(r.Context())
	model.Email = params.ByName("email")

	return nil
}

func (h *supplierUpdateHelper) QueryUpdate(model interface{}) (orm.Result, error) {
	err := validator.ValidateStruct(model)
	if err != nil {
		return nil, err
	}

	result, err := services.GetDB().GetSupplierAccounts().Update(model.(*common.SupplierAccount))
	if err == nil && result.RowsAffected() == 0 {
		return result, errors.New("account does not exist")
	}

	return result, err
}
