package models

import (
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitDB() {
	dsn := os.Getenv("DB_DSN")
	if dsn == "" {
		// Fallback for local development if not in env
		dsn = "host=localhost user=ems password=ems_pass dbname=ems port=5433 sslmode=disable TimeZone=Asia/Shanghai"
	}

	var err error
	maxRetries := 30
	for i := 0; i < maxRetries; i++ {
		DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
		if err == nil {
			break
		}
		log.Printf("Failed to connect to database (attempt %d/%d): %v. Retrying in 2 seconds...", i+1, maxRetries, err)
		time.Sleep(2 * time.Second)
	}

	if err != nil {
		log.Fatal("Failed to connect to database after multiple attempts:", err)
	}

	// Set connection pool settings
	sqlDB, err := DB.DB()
	if err != nil {
		log.Fatal("Failed to get generic database object:", err)
	}

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

	fmt.Println("Database connected successfully")

	// NOTE: AutoMigrate is disabled in favor of SQL migrations (golang-migrate).
	// Please look into backend/db/migrations/ for schema changes.
	
	/*
	err = DB.AutoMigrate(
		&IntegrationSource{},
		&Device{},
		&SysLocation{},
		&AlarmLog{},
		&SysOperLog{},
		&InspectionLedger{},
		&User{},
		&SysRole{},
		&SysUserRole{},
		&SysConfig{},
		&SysMenu{},
		&SysRoleMenu{},
		&EquipmentCleaningFormulaTemplate{},
		&BackupLog{},
		&AlarmRule{},
		&AlarmRuleBinding{},
		&AIAnalysisReport{},
	)
	if err != nil {
		log.Fatal("Failed to migrate database:", err)
	}
	fmt.Println("Database migration completed")
	*/

	// Initialize basic menu data
	// TODO: Consider moving this to SQL migration as well (e.g. 000005_seed_menus.up.sql)
	InitSysMenuData(DB)
}
