package main

import (
	"fmt"
	"log"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func main() {
	// 数据库连接字符串
	dsn := "host=cxd.whcxd.cn port=16159 user=erp_pgsql password=erp_2025 dbname=junhong_cmp_test sslmode=disable"

	// 连接数据库
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("连接数据库失败: %v", err)
	}

	// 验证每个表的索引
	checkTableIndexes(db, "personal_customer_phone")
	checkTableIndexes(db, "personal_customer_iccid")
	checkTableIndexes(db, "personal_customer_device")

	fmt.Println("\n✅ 索引验证成功！")
}

func checkTableIndexes(db *gorm.DB, tableName string) {
	var indexes []struct {
		IndexName  string
		ColumnName string
		IsUnique   bool
	}

	result := db.Raw(`
		SELECT
			i.relname AS index_name,
			a.attname AS column_name,
			ix.indisunique AS is_unique
		FROM
			pg_class t,
			pg_class i,
			pg_index ix,
			pg_attribute a
		WHERE
			t.oid = ix.indrelid
			AND i.oid = ix.indexrelid
			AND a.attrelid = t.oid
			AND a.attnum = ANY(ix.indkey)
			AND t.relkind = 'r'
			AND t.relname = ?
		ORDER BY
			i.relname
	`, tableName).Scan(&indexes)

	if result.Error != nil {
		log.Printf("⚠️  查询表 %s 的索引失败: %v", tableName, result.Error)
		return
	}

	fmt.Printf("\n表 %s 的索引:\n", tableName)
	if len(indexes) == 0 {
		fmt.Println("  (无索引)")
		return
	}

	currentIndex := ""
	for _, idx := range indexes {
		if idx.IndexName != currentIndex {
			uniqueStr := ""
			if idx.IsUnique {
				uniqueStr = " [唯一索引]"
			}
			fmt.Printf("  - %s%s\n", idx.IndexName, uniqueStr)
			currentIndex = idx.IndexName
		}
		fmt.Printf("    └─ %s\n", idx.ColumnName)
	}
}
