// repository/email_repository.go
package repository

import (
	"time"

	"api_bb/internal/models"
	"gorm.io/gorm"
)

type EmailRepository struct {
	db *gorm.DB
}

func NewEmailRepository(db *gorm.DB) *EmailRepository {
	return &EmailRepository{db: db}
}

func (r *EmailRepository) CreateVerificationToken(verification *models.EmailVerification) error {
	return r.db.Create(verification).Error
}

func (r *EmailRepository) GetVerificationToken(token string) (*models.EmailVerification, error) {
	var verification models.EmailVerification
	err := r.db.Where("token = ? AND used = ? AND expires_at > ?", token, false, time.Now()).
		Preload("User").
		First(&verification).Error
	if err != nil {
		return nil, err
	}
	return &verification, nil
}

func (r *EmailRepository) MarkTokenAsUsed(token string) error {
	return r.db.Model(&models.EmailVerification{}).
		Where("token = ?", token).
		Updates(map[string]interface{}{
			"used":       true,
			"updated_at": time.Now(),
		}).Error
}

func (r *EmailRepository) DeleteExpiredTokens() error {
	return r.db.Where("expires_at < ?", time.Now()).Delete(&models.EmailVerification{}).Error
}

func (r *EmailRepository) GetUsersWithNewsletter() ([]models.User, error) {
	var users []models.User
	err := r.db.Where("newsletter = ? AND email_verified = ?", true, true).
		Find(&users).Error
	return users, err
}

// MarkEmailAsVerified помечает email пользователя как верифицированный
func (r *EmailRepository) MarkEmailAsVerified(userID uint) error {
	return r.db.Model(&models.User{}).
		Where("id = ?", userID).
		Updates(map[string]interface{}{
			"email_verified": true,
			"updated_at":     time.Now(),
		}).Error
}

// GetUserByEmail возвращает пользователя по email
func (r *EmailRepository) GetUserByEmail(email string) (*models.User, error) {
	var user models.User
	err := r.db.Where("email = ?", email).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// UpdatePassword обновляет пароль пользователя
func (r *EmailRepository) UpdatePassword(userID uint, newPassword string) error {
	return r.db.Model(&models.User{}).
		Where("id = ?", userID).
		Updates(map[string]interface{}{
			"password":   newPassword,
			"updated_at": time.Now(),
		}).Error
}

