package vdx

import (
	"context"

	"go.mongodb.org/mongo-driver/mongo"
	"golib/v1/features/mlib/ii"
	"golib/v1/features/mlib/mo"
	"golib/v1/features/mlib/validate"
)

func Init(client mo.Handler) {
	ctx, cancel := context.WithTimeout(context.Background(), mo.DefaultTimout)
	defer cancel()

	configure := validate.GetConfigure()

	for name, cfg := range configure {
		item, ok := ii.GetItemByName(name)
		if !ok {
			panic("unknown_item")
		}
		iName := item.GetName()
		// 删除索引
		index := client.Client().Database(iName.DbName()).Collection(iName.CollName()).Indexes()
		if _, err := index.DropAll(ctx); err != nil {
			if cmdErr, ok := err.(mongo.CommandError); ok {
				if cmdErr.Code == 26 { // NamespaceNotFound
					continue
				}
			}
			panic(err)
		}
		if len(cfg.Unique) == 0 {
			continue
		}
		// 设置索引
		_, err := index.CreateMany(ctx, mo.NewIndex(cfg.Unique))
		if err != nil {
			panic(err)
		}
	}
}
