package routers

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

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

func (pr *PublicRouter) refreshAccessToken(r *http.Request) http.HandlerFunc {
	pr.logger.Debug("Processing access token refresh request")
	var req srequest.AccessTokenRefresh
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		pr.logger.Info("Failed to decode token rotation request", zap.Error(err))
		return response.BadPayload(pr.logger, mservice.RefreshTokens, err)
	}

	account, token, err := pr.validateRefreshToken(r.Context(), r, &req)
	if err != nil {
		if errors.Is(err, errClientIPNotAllowed) {
			return response.Forbidden(pr.logger, pr.service, "ip_not_allowed", "request ip is not allowed for this client")
		}
		pr.logger.Warn("Failed to process access token refreshment request", zap.Error(err))
		return response.Auto(pr.logger, pr.service, err)
	}

	return sresponse.Account(pr.logger, account, token)
}
