package main

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

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

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)
	}

	fmt.Println("Connected to 'nl_blog' database successfully!")

	// 1. 确认 lq 用户存在且 role_id 正确
	var userID, roleID int
	var usernameStr string
	err = db.QueryRow("SELECT id, username, role_id FROM users WHERE username = 'lq'").Scan(&userID, &usernameStr, &roleID)
	if err != nil {
		log.Printf("Error finding user 'lq': %v", err)
		// 如果用户不存在，可以尝试修复（可选）
	} else {
		fmt.Printf("User found: %s (ID: %d, RoleID: %d)\n", usernameStr, userID, roleID)
	}

	// 2. 清空并重新填充 role_permissions 表
	// 注意：这里假设 roles 表中 ID 1=admin, 2=editor, 3=viewer
	// 并且 permissions 表已经有数据。如果 permissions 表也是空的，需要先填充 permissions。

	// 先检查 permissions 表是否有数据
	var permCount int
	db.QueryRow("SELECT COUNT(*) FROM permissions").Scan(&permCount)
	if permCount == 0 {
		fmt.Println("Permissions table is empty! Repopulating permissions...")
		// 插入权限数据 (简略版，确保核心权限存在)
		perms := []string{
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Create User', 'users', 'create')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Read User', 'users', 'read')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Update User', 'users', 'update')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Delete User', 'users', 'delete')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Read Dashboard', 'dashboard', 'read')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Create Post', 'posts', 'create')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Read Post', 'posts', 'read')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Update Post', 'posts', 'update')",
			"INSERT INTO `permissions` (`name`, `resource`, `action`) VALUES ('Delete Post', 'posts', 'delete')",
		}
		for _, sql := range perms {
			if _, err := db.Exec(sql); err != nil {
				log.Printf("Error inserting permission: %v", err)
			}
		}
	}

	// 清空 role_permissions
	_, err = db.Exec("DELETE FROM role_permissions")
	if err != nil {
		log.Fatalf("Failed to clear role_permissions: %v", err)
	}

	// 重新关联 Admin (Role ID 1) - 赋予所有权限
	res, err := db.Exec("INSERT INTO role_permissions (role_id, permission_id) SELECT 1, id FROM permissions")
	if err != nil {
		log.Fatalf("Failed to assign permissions to admin: %v", err)
	}
	rowsAffected, _ := res.RowsAffected()
	fmt.Printf("Assigned %d permissions to Admin role.\n", rowsAffected)

	// 重新关联 Editor (Role ID 2) - 赋予 posts 相关权限
	res, err = db.Exec("INSERT INTO role_permissions (role_id, permission_id) SELECT 2, id FROM permissions WHERE resource = 'posts'")
	if err != nil {
		log.Printf("Failed to assign permissions to editor: %v", err)
	}

	fmt.Println("Database permissions fixed successfully!")
}
