package permissionsimp

import (
	"encoding/json"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"github.com/tech/sendico/server/interface/api/sresponse"
	"go.uber.org/zap"
)

func (a *PermissionsAPI) createRoleDescription(r *http.Request, account *model.Account, _ *sresponse.TokenData) http.HandlerFunc {
	var req model.RoleDescription
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		a.logger.Warn("Failed to decode role creation request", zap.Error(err))
		return response.BadPayload(a.logger, mservice.Roles, err)
	}

	if err := a.rdb.Create(r.Context(), &req); err != nil {
		a.logger.Warn("Failed to create role description", zap.Error(err),
			mzap.ObjRef("requesting_account_ref", account.ID), zap.String("role_name", req.Name))
		return response.Auto(a.logger, a.Name(), err)
	}

	return response.Success(a.logger)
}
