package migrasyon

import (
	configs "goFiber/config"
	database "goFiber/database/config"
	"goFiber/database/models"
	"log"
	"net/url"
	"strings"
)

// Only run AutoMigrate if DB is initialized

func Migrate() {
	if database.DB != nil {
		if err := database.DB.AutoMigrate(
			&models.User{},
			&models.SocialAccount{},
			&models.Profile{},
			&models.Hero{},
			&models.Setting{},
			&models.CorsWhitelist{},
			&models.CorsBlacklist{},
			&models.RateLimitSetting{},
			&models.Category{},
			&models.Tag{},
			&models.Post{},
			&models.CategoryView{},
			&models.Comment{},
		); err != nil {
			log.Printf("AutoMigrate Yapılamadı !!: %v", err)
		}
		seedSecurityDefaults()
		log.Println("AutoMigrate Yapıldı.")
	} else {
		log.Println("DB not initialized: skipping AutoMigrate")
	}
}

func seedSecurityDefaults() {
	seedRateLimit("register", "Register endpoint default rate limit", 5, 60)
	seedRateLimit("login", "Login endpoint default rate limit", 10, 60)

	for _, origin := range defaultWhitelistOrigins() {
		seedCorsWhitelist(origin, "default seeded whitelist")
	}
}

func seedRateLimit(name, description string, maxRequests int64, windowSeconds int) {
	var existing models.RateLimitSetting
	if err := database.DB.Where("name = ?", name).First(&existing).Error; err == nil {
		return
	}

	item := models.RateLimitSetting{
		Name:          name,
		Description:   description,
		MaxRequests:   maxRequests,
		WindowSeconds: windowSeconds,
		IsActive:      true,
		UpdatedBy:     "seed",
	}
	if err := database.DB.Create(&item).Error; err != nil {
		log.Printf("RateLimit seed failed (%s): %v", name, err)
		return
	}
	log.Printf("RateLimit seed created: name=%s max=%d window=%ds", name, maxRequests, windowSeconds)
}

func seedCorsWhitelist(origin, description string) {
	origin = strings.TrimSpace(origin)
	if origin == "" {
		return
	}

	var existing models.CorsWhitelist
	if err := database.DB.Where("origin = ?", origin).First(&existing).Error; err == nil {
		return
	}

	item := models.CorsWhitelist{
		Origin:      origin,
		Description: description,
		IsActive:    true,
		CreatedBy:   "seed",
	}
	if err := database.DB.Create(&item).Error; err != nil {
		log.Printf("CorsWhitelist seed failed (%s): %v", origin, err)
		return
	}
	log.Printf("CorsWhitelist seed created: origin=%s", origin)
}

func defaultWhitelistOrigins() []string {
	origins := []string{
		"http://localhost:3000",
		"http://localhost:5173",
		"http://localhost:8080",
	}

	appURL := strings.TrimSpace(configs.AppConfig.AppURL)
	if appURL != "" {
		if parsed, err := url.Parse(appURL); err == nil && parsed.Scheme != "" && parsed.Host != "" {
			origins = append(origins, parsed.Scheme+"://"+parsed.Host)
		}
	}

	uniq := make(map[string]struct{})
	out := make([]string, 0, len(origins))
	for _, origin := range origins {
		origin = strings.TrimSpace(origin)
		if origin == "" {
			continue
		}
		if _, ok := uniq[origin]; ok {
			continue
		}
		uniq[origin] = struct{}{}
		out = append(out, origin)
	}
	return out
}
