package routers

import (
	"context"
	"net/http"

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

func (pr *PublicRouter) refreshAndRespondLogin(
	ctx context.Context,
	r *http.Request,
	session *model.SessionIdentifier,
	account *model.Account,
	accessToken *sresponse.TokenData,
) http.HandlerFunc {
	refreshToken, err := rtokens.PrepareRefreshToken(
		ctx,
		r,
		pr.rtdb,
		pr.config.Length,
		pr.config.Expiration.Refresh,
		session,
		account,
		pr.logger,
	)
	if err != nil {
		pr.logger.Warn("Failed to create refresh token", zap.Error(err), mzap.StorableRef(account),
			zap.String("client_id", session.ClientID), zap.String("device_id", session.DeviceID))
		return response.Internal(pr.logger, pr.service, err)
	}

	token := sresponse.TokenData{
		Token:      refreshToken.RefreshToken,
		Expiration: refreshToken.ExpiresAt,
	}
	return sresponse.Login(pr.logger, account, accessToken, &token)
}
