package services

import (
	"GoMembership/internal/models"
	"GoMembership/internal/utils"
	"GoMembership/pkg/errors"
	"time"
)

func (s *UserService) SetVerificationToken(id *uint, verificationType *string) (string, error) {

	token, err := utils.GenerateVerificationToken()
	if err != nil {
		return "", err
	}

	// Check if user is already verified
	verified, err := s.Repo.IsVerified(id)
	if err != nil {
		return "", err
	}
	if verified {
		return "", errors.ErrAlreadyVerified
	}

	// Prepare the Verification record
	verification := models.Verification{
		UserID:            *id,
		VerificationToken: token,
		Type:              *verificationType,
	}

	return s.Repo.SetVerificationToken(&verification)
}

func (s *UserService) RevokeVerification(id *uint, verificationType string) error {
	return s.Repo.DeleteVerification(*id, verificationType)

}

func (service *UserService) VerifyUser(token *string, verificationType *string) (*models.Verification, error) {
	verification, err := service.Repo.GetVerificationOfToken(token, verificationType)
	if err != nil {
		return nil, err
	}

	// Check if the user is already verified
	verified, err := service.Repo.IsVerified(&verification.UserID)
	if err != nil {
		return nil, err
	}
	if verified {
		return nil, errors.ErrAlreadyVerified
	}
	t := time.Now()
	verification.VerifiedAt = &t

	return verification, nil
}
