package db

import (
	"log"
	"mohportal/models"

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

var DB *gorm.DB

// ConnectDatabase connects to the database and runs migrations
func ConnectDatabase(url string) {
	var err error

	DB, err = gorm.Open(postgres.Open(url), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	// Run migrations
	err = DB.AutoMigrate(
		&models.Tenant{},
		&models.User{},
		&models.OIDCIdentity{},
		&models.SocialIdentity{},
		&models.JobPosition{},
		&models.Resume{},
		&models.Application{},
	)
	if err != nil {
		log.Fatal("Failed to migrate database:", err)
	}

	log.Println("Database connected and migrated successfully")
}