// 数据库连接管理 + GORM AutoMigrate
package database

import (
	"log"

	"com.sclktx/m/v2/internal/common/model"
	"com.sclktx/m/v2/internal/pkg/config"

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

var DB *gorm.DB

// InitDB 初始化 PostgreSQL 连接并执行自动迁移
func InitDB(cfg *config.DatabaseConfig) *gorm.DB {
	var err error
	logLevel := logger.Info

	if cfg.SSLMode == "" {
		cfg.SSLMode = "disable"
	}

	DB, err = gorm.Open(postgres.Open(cfg.DSN()), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logLevel),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	if err := AutoMigrate(DB); err != nil {
		log.Fatalf("Failed to auto migrate: %v", err)
	}

	return DB
}

// AutoMigrate 自动迁移所有模型对应的数据库表
func AutoMigrate(db *gorm.DB) error {
	return db.AutoMigrate(
		&model.User{},
		&model.Visitor{},
		&model.Appointment{},
		&model.VisitRecord{},
		&model.Invitation{},
		&model.Banner{},
		&model.InviteCode{},
		&model.Notice{},
		&model.Notification{},
		&model.AdminUser{},
		&model.Department{},
		&model.EmployeeCertification{},
		// 工作流引擎
		&model.ProcessDefinition{},
		&model.ProcessInstance{},
		&model.Task{},
		&model.GoodsTemplate{},
		&model.VehicleInfo{},
		&model.UserDepartment{},
		&model.VisitorArea{},
		&model.VisitType{},
		&model.PendingEmployee{},
		&model.GlobalApprover{},
	)
}

func GetDB() *gorm.DB {
	return DB
}
