package main

import (
	"fmt"
	"log"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

func main() {
	db, err := gorm.Open(sqlite.Open("e:/Project/MeshRay/data/meshray.db"), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("=== MeshRay 数据库表结构检查 ===")

	// 检查所有表是否存在
	tables := []string{
		"networks",
		"devices",
		"policies",
		"services",
		"mesh_seeds",
		"pending_joins",
		"alert_rules",
		"audit_logs",
		"users",
		"system_configs",
		"ddns_configs",
		"network_members",
		"security_keys",
		"system_settings",
		"external_services",
		"turn_configs", // 这个应该不存在
	}

	for _, table := range tables {
		query := fmt.Sprintf("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='%s'", table)
		var count int64
		db.Raw(query).Scan(&count)

		if count > 0 {
			fmt.Printf("✅ %s: 存在\n", table)

			// 显示字段信息
			showTableSchema(db, table)
		} else {
			fmt.Printf("❌ %s: 不存在\n", table)
		}
	}
}

func showTableSchema(db *gorm.DB, tableName string) {
	rows, err := db.Raw(fmt.Sprintf("PRAGMA table_info(%s)", tableName)).Rows()
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var cid, notnull int
		var name, typ string
		var dflt_value interface{}
		var pk int

		rows.Scan(&cid, &name, &typ, &notnull, &dflt_value, &pk)
		fmt.Printf("   - %s (%s) [pk=%d, notnull=%d]\n", name, typ, pk, notnull)
	}
}
