package accountapiimp

import (
	"errors"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/merrors"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.uber.org/zap"
)

func (a *AccountAPI) verify(r *http.Request) http.HandlerFunc {
	// Validate user input
	token := mutil.GetToken(r)
	// Get user
	ctx := r.Context()
	user, err := a.db.GetByToken(ctx, token)
	if errors.Is(err, merrors.ErrNoData) {
		a.logger.Debug("Verification token not found", zap.Error(err))
		return a.reportTokenNotFound()
	}
	if err != nil {
		a.logger.Warn("Failed to fetch account", zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}

	// Delete verification token to confirm account
	user.VerifyToken = ""
	if err = a.db.Update(ctx, user); err != nil {
		a.logger.Warn("Failed to save account while verifying account", zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}

	// TODO: Send verification confirmation email
	return response.Success(a.logger)
}

func (a *AccountAPI) resendVerificationMail(r *http.Request) http.HandlerFunc {
	return a.sendVerificationMail(r, getID)
}

func (a *AccountAPI) resendVerification(r *http.Request) http.HandlerFunc {
	return a.sendVerificationMail(r, getEmail)
}
