package repo

import (
	"errors"
	"time"

	"trustcontact/internal/models"

	"gorm.io/gorm"
)

type PasswordResetTokenRepo struct {
	db *gorm.DB
}

func NewPasswordResetTokenRepo(db *gorm.DB) *PasswordResetTokenRepo {
	return &PasswordResetTokenRepo{db: db}
}

func (r *PasswordResetTokenRepo) Create(token *models.PasswordResetToken) error {
	return r.db.Create(token).Error
}

func (r *PasswordResetTokenRepo) FindValidByHash(tokenHash string, now time.Time) (*models.PasswordResetToken, error) {
	var token models.PasswordResetToken
	err := r.db.Where("token_hash = ? AND expires_at > ?", tokenHash, now).First(&token).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &token, nil
}

func (r *PasswordResetTokenRepo) DeleteByID(id string) error {
	return r.db.Delete(&models.PasswordResetToken{}, id).Error
}

func (r *PasswordResetTokenRepo) DeleteByUserID(userID string) error {
	return r.db.Where("user_id = ?", userID).Delete(&models.PasswordResetToken{}).Error
}
