package database

import (
	"fmt"
	"log"
	"time"

	"github.com/tapper/backend/models"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func Connect(databaseURL string) error {
	var err error
	DB, err = gorm.Open(postgres.Open(databaseURL), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Warn),
		NowFunc: func() time.Time {
			return time.Now().UTC()
		},
	})
	if err != nil {
		return fmt.Errorf("failed to connect to database: %w", err)
	}

	sqlDB, err := DB.DB()
	if err != nil {
		return fmt.Errorf("failed to get underlying sql.DB: %w", err)
	}

	sqlDB.SetMaxOpenConns(25)
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetConnMaxLifetime(5 * time.Minute)

	if err := runMigrations(); err != nil {
		return fmt.Errorf("auto-migration failed: %w", err)
	}

	log.Println("[database] Connected and migrated successfully")
	return nil
}

func runMigrations() error {
	return DB.AutoMigrate(
		&models.User{},
		&models.RefreshToken{},
		&models.Match{},
		&models.MatchPlayer{},
		&models.MatchPlayerStats{},
		&models.QueueEntry{},
		&models.GameServer{},
		&models.PortPool{},
		&models.Penalty{},
		&models.Ban{},
		&models.StaffNote{},
		&models.Ticket{},
		&models.TicketMessage{},
		&models.EloConfig{},
		&models.MMRHistory{},
		&models.AuditLog{},
		&models.PlatformConfig{},
	)
}
