package repositories

import (
	"GoMembership/internal/constants"
	"GoMembership/internal/database"
	"GoMembership/internal/models"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func (ur *UserRepository) IsVerified(userID *uint) (bool, error) {
	var user models.User
	result := database.DB.Select("status").First(&user, userID)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return false, gorm.ErrRecordNotFound
		}
		return false, result.Error
	}
	return user.Status > constants.DisabledStatus, nil
}

func (ur *UserRepository) GetVerificationOfToken(token *string, verificationType *string) (*models.Verification, error) {

	var emailVerification models.Verification
	result := database.DB.Where("verification_token = ? AND type = ?", token, verificationType).First(&emailVerification)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, gorm.ErrRecordNotFound
		}
		return nil, result.Error
	}
	return &emailVerification, nil
}

func (ur *UserRepository) SetVerificationToken(verification *models.Verification) (token string, err error) {

	result := database.DB.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "user_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"verification_token", "created_at", "type"}),
	}).Create(&verification)

	if result.Error != nil {
		return "", result.Error
	}

	return verification.VerificationToken, nil
}

func (ur *UserRepository) DeleteVerification(id uint, verificationType string) error {
	result := database.DB.Where("user_id = ? AND type = ?", id, verificationType).Delete(&models.Verification{})
	if result.Error != nil {
		return result.Error
	}
	return nil
}
