package database

import (
	"log"

	"fotbal-club/internal/models"
	"fotbal-club/pkg/utils"

	"gorm.io/gorm"
)

// MigrateDB runs database migrations
func MigrateDB(db *gorm.DB) error {
	// Enable UUID extension
	err := db.Exec(`
		CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
		CREATE EXTENSION IF NOT EXISTS "pgcrypto";
	`).Error
	if err != nil {
		return err
	}

	// Drop existing tables if they exist
	err = db.Migrator().DropTable(
		&models.User{},
		&models.Article{},
		&models.Category{},
		&models.Team{},
		&models.Player{},
		&models.Sponsor{},
		&models.Settings{},
		&models.MatchOverride{},
		&models.TeamLogoOverride{},
		&models.ContactMessage{},
		&models.PasswordReset{},
		&models.ArticleMatchLink{},
		&models.ScoreboardState{},
		&models.ContactCategory{},
		&models.Contact{},
		&models.PageElementConfig{},
	)
	if err != nil {
		return err
	}

	// Auto migrate all models
	err = db.AutoMigrate(
		&models.User{},
		&models.Article{},
		&models.Category{},
		&models.Team{},
		&models.Player{},
		&models.Sponsor{},
		&models.Settings{},
		&models.MatchOverride{},
		&models.TeamLogoOverride{},
		&models.ContactMessage{},
		&models.PasswordReset{},
		&models.ArticleMatchLink{},
		&models.ScoreboardState{},
		&models.ContactCategory{},
		&models.Contact{},
		&models.PageElementConfig{},
	)
	if err != nil {
		return err
	}

	// Add indexes
	err = db.Exec(`
		CREATE INDEX IF NOT EXISTS idx_users_email ON users (email);
		CREATE INDEX IF NOT EXISTS idx_articles_category_id ON articles (category_id);
		CREATE INDEX IF NOT EXISTS idx_articles_author_id ON articles (author_id);
		CREATE INDEX IF NOT EXISTS idx_password_resets_user_id ON password_resets (user_id);
		CREATE UNIQUE INDEX IF NOT EXISTS ux_password_resets_token ON password_resets (token);
	`).Error
	if err != nil {
		return err
	}

	log.Println("Database migration completed successfully")
	return nil
}

// SeedDB populates the database with initial data
func SeedDB(db *gorm.DB) error {
	// Check if we already have data
	var count int64
	db.Model(&models.User{}).Count(&count)
	if count > 0 {
		log.Println("Database already seeded, skipping...")
		return nil
	}

	// Hash the admin password
	hashedPassword, err := utils.HashPassword("admin123")
	if err != nil {
		return err
	}

	// Create default admin user
	admin := models.User{
		Email:     "admin@fotbalclub.cz",
		Password:  hashedPassword,
		FirstName: "Admin",
		LastName:  "User",
		Role:      "admin",
	}

	if err := db.Create(&admin).Error; err != nil {
		return err
	}

	// Create default test user
	hashedPassword, err = utils.HashPassword("user123")
	if err != nil {
		return err
	}

	user := models.User{
		Email:     "user@fotbalclub.cz",
		Password:  hashedPassword,
		FirstName: "Test",
		LastName:  "User",
		Role:      "user",
	}

	if err := db.Create(&user).Error; err != nil {
		return err
	}

	// Create default categories
	categories := []models.Category{
		{Name: "Novinky", Description: "Aktuální novinky z klubu"},
		{Name: "Zápasy", Description: "Zápasy a výsledky"},
		{Name: "Tabulka", Description: "Soutěžní tabulka"},
		{Name: "Tiskové zprávy", Description: "Oficiální tiskové zprávy"},
	}

	for _, category := range categories {
		if err := db.FirstOrCreate(&category, models.Category{Name: category.Name}).Error; err != nil {
			return err
		}
	}

	// Create sample team
	team := models.Team{
		Name:        "FK Fotbal Club",
		ShortName:   "FKFC",
		Description: "Hlavní tým FK Fotbal Clubu",
		IsActive:    true,
	}

	if err := db.Create(&team).Error; err != nil {
		return err
	}

	// Create sample players
	players := []models.Player{
		{
			FirstName:    "Jan",
			LastName:     "Novák",
			Position:     "Brankář",
			JerseyNumber: 1,
			TeamID:       team.ID,
			IsActive:     true,
		},
		{
			FirstName:    "Petr",
			LastName:     "Svoboda",
			Position:     "Obránce",
			JerseyNumber: 5,
			TeamID:       team.ID,
			IsActive:     true,
		},
	}

	for _, player := range players {
		if err := db.Create(&player).Error; err != nil {
			return err
		}
	}

	// Create sample sponsors
	sponsors := []models.Sponsor{
		{
			Name:       "Hlavní partner",
			WebsiteURL: "https://example.com",
			IsActive:   true,
		},
		{
			Name:       "Oficiální výstroj",
			WebsiteURL: "https://sportovni-vyrobce.cz",
			IsActive:   true,
		},
	}

	for _, sponsor := range sponsors {
		if err := db.Create(&sponsor).Error; err != nil {
			return err
		}
	}

	log.Println("Database seeding completed successfully")
	return nil
}
