package db

import (
	"cangui/whatsapp/backend/models"
	"fmt"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)


func InitDB() *gorm.DB {
    host := os.Getenv("DB_HOST")
    port := os.Getenv("DB_PORT")
    user := os.Getenv("DB_USER")
    pass := os.Getenv("DB_PASS")
    name := os.Getenv("DB_NAME")

    dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&charset=utf8mb4&loc=Local", user, pass, host, port, name)

    var db *gorm.DB
    var err error

    // Retry loop (attente de MariaDB)
    for i := 0; i < 10; i++ {
        db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
        if err == nil {
            break
        }

        fmt.Printf("⏳ Tentative %d: BDD pas encore prête (%s)\n", i+1, err)
        time.Sleep(3 * time.Second)
    }

    if err != nil {
        panic("❌ Failed to connect to database: " + err.Error())
    }

    fmt.Println("✅ Connexion à MariaDB réussie !")
    err = db.AutoMigrate(
        &models.User{},
        &models.Consumption{},
        &models.MonthlyConsumption{},
        &models.Conversation{},
    )
    if err != nil {
        panic("Migration failed: " + err.Error())
    }

    return db
}

