package test

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

	"time"
)

func setupDB() (*sql.DB, error) {
	db, err := sql.Open("xugusql", "IP=10.28.20.101;"+
		"DB=GODB;User=SYSDBA;PWD=SYSDBA;"+
		"Port= 5190;AUTO_COMMIT=on;CHAR_SET=UTF8")
	if err != nil {
		return nil, err
	}
	return db, nil
}

// TestStability 测试数据库的稳定性
func TestStability(t *testing.T) {
	db, err := setupDB()
	if err != nil {
		t.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	duration := 1 * time.Hour // 测试运行时间
	endTime := time.Now().Add(duration)
	// 创建日志文件
	logFile, err := os.OpenFile("stability_test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("Failed to open log file: %v", err)
	}
	defer logFile.Close()

	// 设置日志输出到文件
	log.SetOutput(logFile)
	for time.Now().Before(endTime) {
		// 执行插入操作
		stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)")
		if err != nil {
			t.Fatalf("Failed to prepare insert statement: %v", err)
			log.Fatalf("Failed to prepare insert statement: %v", err)
		}
		_, err = stmt.Exec("TestUser")
		stmt.Close()
		if err != nil {
			t.Fatalf("Failed to execute insert statement: %v", err)
			log.Fatalf("Failed to execute insert statement: %v", err)

		}

		// 执行查询操作
		stmt, err = db.Prepare("SELECT name FROM users WHERE name = ?")
		if err != nil {
			t.Fatalf("Failed to prepare select statement: %v", err)
			log.Fatalf("Failed to prepare select statement: %v", err)
		}
		var name string
		err = stmt.QueryRow("TestUser").Scan(&name)
		stmt.Close()
		if err != nil {
			t.Fatalf("Failed to query row: %v", err)
			log.Fatalf("Failed to prepare select statement: %v", err)
		}

		if name != "TestUser" {
			t.Errorf("Expected name 'TestUser', but got '%s'", name)
			log.Fatalf("Failed to prepare select statement: %v", err)
		}

		// 执行删除操作
		stmt, err = db.Prepare("DELETE FROM users WHERE name = ?")
		if err != nil {
			t.Fatalf("Failed to prepare delete statement: %v", err)
			log.Fatalf("Failed to prepare select statement: %v", err)
		}
		_, err = stmt.Exec("TestUser")
		stmt.Close()
		if err != nil {
			t.Fatalf("Failed to execute delete statement: %v", err)
			log.Fatalf("Failed to prepare select statement: %v", err)
		}
	}
}
