package database

import (
	"api_es/internal/config"
	"api_es/internal/models"
	"api_es/pkg/logger"
	"fmt"

	"go.uber.org/zap"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func NewPostgresConnection(cfg *config.Config) (*gorm.DB, error) {
	zapLogger := logger.Get()
	zapLogger.Info("Start connect to Postgres DB")
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=UTC",
		cfg.DBHost, cfg.DBUser, cfg.DBPassword, cfg.DBName, cfg.DBPort)
	zapLogger.Info("dsn = %s", zap.String("dsn", dsn))

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, fmt.Errorf("failed to connect to database: %w", err)
	}

	zapLogger.Info("AutoMigrate models")
	// Автомиграция
	if err := autoMigrate(db); err != nil {
        zapLogger.Error("can't migrate models, error = %s", zap.Error(err))
		return nil, fmt.Errorf("can't migrate models, error = %s", err)
	}
	zapLogger.Info("Migrate complite successfully")

    zapLogger.Info("Fill init data")
    SeedInitialData(db)

    zapLogger.Info("Successfully connected to database")
	return db, nil
}

func autoMigrate(db *gorm.DB) error {
    zapLogger := logger.Get()
    zapLogger.Debug("Start migration")
	models := []interface{}{
		&models.User{},
		&models.Object{},
		&models.ObjectImage{},
		&models.Amenity{},
		&models.ObjectAmenity{},
	}

	for _, model := range models {
		if err := db.AutoMigrate(model); err != nil {
			return fmt.Errorf("failed to migrate %T: %w", model, err)
		}
	}

    zapLogger.Debug("End migration seccessfully")
	return nil
}
