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"
	"go.uber.org/zap"
)

func (pr *PublicRouter) rotateRefreshToken(r *http.Request) http.HandlerFunc {
	pr.logger.Debug("Processing token rotation request...")
	var req srequest.TokenRefreshRotate
	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 validate refresh token", zap.Error(err))
		return response.Auto(pr.logger, pr.service, err)
	}

	return pr.refreshAndRespondLogin(r.Context(), r, &req.SessionIdentifier, account, token)
}
