package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// 从环境变量或默认值获取数据库配置
	host := getEnv("DB_HOST", "mysql1.rdsmbk3ednsgnnt.rds.bj.baidubce.com")
	port := getEnv("DB_PORT", "3306")
	user := getEnv("DB_USER", "root_dev")
	password := getEnv("DB_PASSWORD", "Kdse89sd")
	dbname := getEnv("DB_NAME", "crm_db")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", user, password, host, port, dbname)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("连接数据库失败: %v", err)
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		log.Fatalf("数据库连接测试失败: %v", err)
	}
	log.Println("✅ 数据库连接成功")

	// 检查 source 列是否存在
	var columnExists bool
	err = db.QueryRow(`
		SELECT COUNT(*) > 0 
		FROM information_schema.COLUMNS 
		WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'trial_periods' AND COLUMN_NAME = 'source'
	`, dbname).Scan(&columnExists)

	if err != nil {
		log.Fatalf("检查列是否存在失败: %v", err)
	}

	if columnExists {
		log.Println("✅ source 列已存在，无需迁移")
		return
	}

	// 添加 source 列
	_, err = db.Exec(`ALTER TABLE trial_periods ADD COLUMN source VARCHAR(255) DEFAULT '' AFTER customer_name`)
	if err != nil {
		log.Fatalf("添加 source 列失败: %v", err)
	}

	log.Println("✅ 成功添加 source (客户来源) 列到 trial_periods 表")
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}
