package models

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

var DBService *gorm.DB

func New(dsn string) error {
	// 启用 Gorm 跨驱动错误翻译，业务层无需解析 Postgres 错误文本或 SQLSTATE。
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true})
	if err != nil {
		return err
	}

	if err := AutoMigrate(db); err != nil {
		return err
	}

	DBService = db
	return nil
}

func AutoMigrate(database *gorm.DB) error {
	if err := database.AutoMigrate(
		&SenlinAgentSchemaMigration{},
		&SenlinAgentUser{},
		&SenlinAgentProject{},
		&SenlinAgentInboxItem{},
		&SenlinAgentInboxSuggestion{},
		&SenlinAgentTask{},
		&SenlinAgentNote{},
		&SenlinAgentSource{},
		&SenlinAgentAISession{},
		&SenlinAgentTag{},
		&SenlinAgentProjectChannel{},
		&SenlinAgentCronPlan{},
		&SenlinAgentProjectEvent{},
		&SenlinAgentAIKey{},
		&SenlinAgentAICallLog{},
		&SenlinAgentAIRateBucket{},
		&SenlinAgentTaskShare{},
	); err != nil {
		return err
	}
	return runVersionedMigrations(database)
}
