package storage

import (
	"errors"

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

	"sproutgate-backend/internal/models"
)

func (s *Store) SaveSecondaryVerification(record models.SecondaryEmailVerification) error {
	row := dbSecondaryFromModel(record)
	return s.db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&row).Error
}

func (s *Store) GetSecondaryVerification(account string, email string) (models.SecondaryEmailVerification, bool, error) {
	var row DBSecondaryEmailVerification
	result := s.db.First(&row, "account = ? AND email = ?", account, email)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return models.SecondaryEmailVerification{}, false, nil
	}
	if result.Error != nil {
		return models.SecondaryEmailVerification{}, false, result.Error
	}
	return row.toModel(), true, nil
}

func (s *Store) DeleteSecondaryVerification(account string, email string) error {
	return s.db.Delete(&DBSecondaryEmailVerification{}, "account = ? AND email = ?", account, email).Error
}
