package main

import (
	"fmt"
	"log"

	"verification-platform-backend/internal/database"

	"gorm.io/gorm"
)

func main() {
	database.Init()
	db := database.DB

	log.Println("开始迁移：统一收费模式为余额")

	if err := addColumnsSQLite(db); err != nil {
		log.Fatalf("添加列失败: %v", err)
	}

	if err := updateBillingType(db); err != nil {
		log.Fatalf("更新billing_type失败: %v", err)
	}

	log.Println("迁移完成！")
}

func columnExists(db *gorm.DB, table, column string) bool {
	var count int64
	db.Raw("SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?", table, column).Scan(&count)
	return count > 0
}

func addColumnsSQLite(db *gorm.DB) error {
	log.Println("添加新列...")

	if !columnExists(db, "app_users", "balance") {
		if err := db.Exec("ALTER TABLE app_users ADD COLUMN balance DECIMAL(10,2) DEFAULT 0").Error; err != nil {
			return fmt.Errorf("添加app_users.balance列失败: %w", err)
		}
		log.Println("添加app_users.balance列成功")
	} else {
		log.Println("app_users.balance列已存在")
	}

	if !columnExists(db, "applications", "deduction_cycle") {
		if err := db.Exec("ALTER TABLE applications ADD COLUMN deduction_cycle VARCHAR(20) DEFAULT 'per_use'").Error; err != nil {
			return fmt.Errorf("添加applications.deduction_cycle列失败: %w", err)
		}
		log.Println("添加applications.deduction_cycle列成功")
	} else {
		log.Println("applications.deduction_cycle列已存在")
	}

	if !columnExists(db, "applications", "deduction_amount") {
		if err := db.Exec("ALTER TABLE applications ADD COLUMN deduction_amount DECIMAL(10,2) DEFAULT 1").Error; err != nil {
			return fmt.Errorf("添加applications.deduction_amount列失败: %w", err)
		}
		log.Println("添加applications.deduction_amount列成功")
	} else {
		log.Println("applications.deduction_amount列已存在")
	}

	if !columnExists(db, "applications", "trial_balance") {
		if err := db.Exec("ALTER TABLE applications ADD COLUMN trial_balance DECIMAL(10,2) DEFAULT 0").Error; err != nil {
			return fmt.Errorf("添加applications.trial_balance列失败: %w", err)
		}
		log.Println("添加applications.trial_balance列成功")
	} else {
		log.Println("applications.trial_balance列已存在")
	}

	return nil
}

func updateBillingType(db *gorm.DB) error {
	log.Println("更新billing_type...")

	result := db.Exec("UPDATE applications SET billing_type = 'count' WHERE billing_type = 'point'")
	if result.Error != nil {
		return fmt.Errorf("更新billing_type失败: %w", result.Error)
	}
	log.Printf("更新了 %d 个应用的billing_type从point到count", result.RowsAffected)

	return nil
}
