package seeder

import (
	dbConfig "ares/database/config"
	"ares/database/models"
	"errors"
	"fmt"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// Seed checks for essential data and creates it if missing
func Seed() {
	seedAdmin()
}

func seedAdmin() {
	// Include soft-deleted records in lookup
	var existing models.User
	err := dbConfig.DB.Unscoped().Where("email = ?", "admin@example.com").First(&existing).Error
	if err == nil {
		// Found a user (could be soft-deleted)
		// If soft-deleted, restore it
		if existing.DeletedAt.Valid {
			// Restore (set deleted_at to NULL) and ensure admin/verified flags
			updateErr := dbConfig.DB.Unscoped().Model(&existing).Updates(map[string]interface{}{
				"deleted_at":     nil,
				"is_admin":       true,
				"email_verified": true,
			}).Error
			if updateErr != nil {
				fmt.Println("Admin restore hatası:", updateErr)
				return
			}
		}
		// user exists or restored, nothing more to do
		return
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		fmt.Println("Admin seed lookup error:", err)
		return
	}

	// If not found at all, create
	password := "password123"
	hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	isTrue := true

	admin := models.User{
		UserName:      "Admin",
		Email:         "admin@example.com",
		Password:      string(hashedPassword),
		IsAdmin:       &isTrue,
		EmailVerified: &isTrue,
	}

	res := dbConfig.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&admin)
	if res.Error != nil {
		fmt.Println("Admin seed hatası:", res.Error)
		return
	}

	if res.RowsAffected == 0 {
		// Another process likely created it concurrently
		fmt.Println("Admin kullanıcı zaten mevcut; seed atlandı.")
		return
	}

	fmt.Println("------------------------------------------------")
	fmt.Println("Admin kullanıcısı oluşturuldu:")
	fmt.Println("Email: admin@example.com")
	fmt.Println("Şifre: password123")
	fmt.Println("------------------------------------------------")
}
