package config

import (
	"fmt"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"github.com/gouki/lunar-server/internal/model"
)

var DB *gorm.DB

// InitDB 初始化数据库连接
func InitDB(cfg *Config) error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.Database.User,
		cfg.Database.Password,
		cfg.Database.Host,
		cfg.Database.Port,
		cfg.Database.Name,
	)

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

	// 自动迁移
	if err := autoMigrate(); err != nil {
		return fmt.Errorf("failed to migrate database: %w", err)
	}

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

// autoMigrate 自动迁移数据库表
func autoMigrate() error {
	if err := DB.AutoMigrate(
		&model.User{},
		&model.UserProfile{},
		&model.BirthProfile{},
		&model.Order{},
		&model.OrderItem{},
		&model.WishTree{},
		&model.Wish{},
		&model.WishProduct{},
	); err != nil {
		return err
	}

	// 初始化默认数据
	return seedDefaultData()
}

// seedDefaultData 初始化默认数据
func seedDefaultData() error {
	// 补充已有许愿树的背景图（新增字段后老数据为空）
	if err := DB.Model(&model.WishTree{}).
		Where("image = '' OR image IS NULL").
		Update("image", "/images/trees/tree-1.jpg").Error; err != nil {
		return err
	}

	// 检查是否已有许愿树数据
	var count int64
	DB.Model(&model.WishTree{}).Count(&count)
	if count > 0 {
		return nil // 已有数据，跳过
	}

	// 插入默认许愿树
	trees := []model.WishTree{
		{Name: "祈福树", Description: "许下美好愿望，祈福平安顺遂", Type: "pine", Image: "/images/trees/tree-1.jpg", MaxWishes: 100, Sort: 0, Status: 1},
		{Name: "姻缘树", Description: "祈求姻缘美满，爱情甜蜜", Type: "sakura", Image: "/images/trees/tree-1.jpg", MaxWishes: 50, Sort: 1, Status: 1},
		{Name: "事业树", Description: "祈愿事业顺利，步步高升", Type: "bamboo", Image: "/images/trees/tree-1.jpg", MaxWishes: 80, Sort: 2, Status: 1},
	}
	if err := DB.Create(&trees).Error; err != nil {
		return err
	}

	// 插入默认许愿商品
	products := []model.WishProduct{
		{Name: "普通许愿条", Description: "基础许愿条，展示7天", Price: 100, Duration: 7, Position: 0, Status: 1},
		{Name: "精品许愿条", Description: "精品许愿条，展示30天，优先位置", Price: 500, Duration: 30, Position: 10, Status: 1},
		{Name: "至尊许愿条", Description: "至尊许愿条，展示90天，置顶显示", Price: 2000, Duration: 90, Position: 100, Status: 1},
	}
	if err := DB.Create(&products).Error; err != nil {
		return err
	}

	log.Println("Default data seeded successfully")
	return nil
}

// GetDB 获取数据库连接
func GetDB() *gorm.DB {
	return DB
}
