package main

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

	_ "github.com/go-sql-driver/mysql"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	// MySQL连接信息
	username := "root"
	password := "root"
	hostname := "127.0.0.1"
	port := "3306"
	dbname := "nl_blog"

	// 构建DSN
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, hostname, port, dbname)

	// 连接到数据库
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Failed to open database connection: %v", err)
	}
	defer db.Close()

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

	targetUser := "lq"
	newPassword := "qiqi991012"

	// 生成哈希密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		log.Fatalf("Failed to hash password: %v", err)
	}

	// 更新密码
	query := "UPDATE users SET password_hash = ? WHERE username = ?"
	res, err := db.Exec(query, string(hashedPassword), targetUser)
	if err != nil {
		log.Fatalf("Failed to update password: %v", err)
	}

	rowsAffected, _ := res.RowsAffected()
	if rowsAffected == 0 {
		fmt.Printf("User '%s' not found or password not changed.\n", targetUser)
	} else {
		fmt.Printf("Password for user '%s' updated successfully.\n", targetUser)
	}
}
