package config

import (
	"context"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

// DBStructure 数据库结构信息
type DBStructure struct {
	Databases []DatabaseInfo `json:"databases"`
}

// DatabaseInfo 数据库信息
type DatabaseInfo struct {
	Name        string          `json:"name"`
	Collections []CollInfo      `json:"collections"`
}

// CollInfo 集合信息
type CollInfo struct {
	Name    string      `json:"name"`
	Count   int64       `json:"count"`
	Sample  interface{} `json:"sample,omitempty"` // 采样一条文档看结构
}

// GetDBStructure 获取 MongoDB 数据结构
func GetDBStructure() (*DBStructure, error) {
	if MongoClient == nil {
		return nil, nil
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 列出所有数据库（排除系统库）
	dbs, err := MongoClient.ListDatabaseNames(ctx, bson.M{
		"name": bson.M{"$nin": []string{"admin", "config", "local"}},
	})
	if err != nil {
		return nil, err
	}

	result := &DBStructure{Databases: make([]DatabaseInfo, 0, len(dbs))}

	for _, dbName := range dbs {
		db := MongoClient.Database(dbName)
		colls, err := db.ListCollectionNames(ctx, bson.M{})
		if err != nil {
			continue
		}

		dbInfo := DatabaseInfo{
			Name:        dbName,
			Collections: make([]CollInfo, 0, len(colls)),
		}

		for _, collName := range colls {
			coll := db.Collection(collName)
			count, _ := coll.CountDocuments(ctx, bson.M{})

			// 采样一条文档
			var sample bson.M
			_ = coll.FindOne(ctx, bson.M{}).Decode(&sample)

			dbInfo.Collections = append(dbInfo.Collections, CollInfo{
				Name:   collName,
				Count:  count,
				Sample: sample,
			})
		}

		result.Databases = append(result.Databases, dbInfo)
	}

	return result, nil
}
