package utils

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"sale/internal/config"
	"sale/internal/models"

	sqlite "github.com/glebarez/sqlite"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func InitDB() {
	var err error
	cfg := config.AppConfig.Database

	switch cfg.Driver {
	case "mysql":
		dsn := fmt.Sprintf(
			"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DBName,
		)
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})
	case "postgres":
		dsn := fmt.Sprintf(
			"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
			cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode,
		)
		DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})
	default:
		dbDir := filepath.Dir(cfg.FilePath)
		if dbDir != "." && dbDir != "/" {
			if err := os.MkdirAll(dbDir, 0755); err != nil {
				log.Fatalf("Failed to create database directory %s: %v", dbDir, err)
			}
			log.Printf("Database directory ensured: %s", dbDir)
		}
		DB, err = gorm.Open(sqlite.Open(cfg.FilePath), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})
	}

	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	log.Printf("Database connected successfully (driver: %s, path: %s)", cfg.Driver, cfg.FilePath)
}

func AutoMigrate() {
	err := DB.AutoMigrate(
		&models.User{},
		&models.Category{},
		&models.Brand{},
		&models.Product{},
		&models.ProductCustomField{},
		&models.Inventory{},
		&models.Cart{},
		&models.Order{},
		&models.OrderItem{},
		&models.Address{},
		&models.Lottery{},
		&models.LotteryPrize{},
		&models.LotteryParticipant{},
		&models.LotteryWinner{},
		&models.Ticket{},
		&models.SystemSetting{},
		&models.SupplierAuthorization{},
		&models.Article{},
		&models.Banner{},
		&models.PaymentChannel{},
	)
	if err != nil {
		log.Fatalf("Failed to migrate database: %v", err)
	}

	var userCount int64
	DB.Model(&models.User{}).Count(&userCount)
	log.Printf("Database migrated successfully (users: %d)", userCount)
}
