package mdb

import (
	"context"
	"log"

	"github.com/mhaya/game/game_cluster/internal/constant"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func SetIndex() {
	err := SetCashOutRecordIndex()
	if err != nil {
		log.Println(err)
	}
	err = SetPlayerIndex()
	if err != nil {
		log.Println(err)
	}
	err = SetPlayerDailyRecordIndex()
	if err != nil {
		log.Println(err)
	}
	err = SetCNameAccountIndex()
	if err != nil {
		log.Println(err)
	}
}

func Unique(indexModel mongo.IndexModel, tableName string) error {
	_, err := MDB.Collection(tableName).Indexes().CreateOne(context.Background(), indexModel)
	if err != nil {
		return err
	}
	return nil
}

// Index 普通的联合索引
func Index(indexModel mongo.IndexModel, tableName string) error {
	_, err := MDB.Collection(tableName).Indexes().CreateOne(context.Background(), indexModel)
	if err != nil {
		return err
	}

	return nil
}

func SetCashOutRecordIndex() error {
	keys := bson.D{
		{"userName", 1},
		{"nickName", 1},
		{"status", 1},
		{"type", 1},
	}
	indexModel := mongo.IndexModel{
		Keys: keys,
	}
	err := Index(indexModel, constant.CNameCashOutRecord)
	if err != nil {
		return err
	}
	return nil
}

func SetPlayerIndex() error {

	keysUnique1 := bson.D{
		{"openId", 1},
	}
	indexModelUnique := mongo.IndexModel{
		Keys: keysUnique1, // 1 表示升序，-1 表示降序
	}
	err := Index(indexModelUnique, constant.CNamePlayer)
	if err != nil {
		return err
	}
	return nil

}

func SetPlayerDailyRecordIndex() error {
	keys := bson.D{
		{"userName", 1},
		{"status", 1},
		{"type", 1},
	}
	indexModel := mongo.IndexModel{
		Keys: keys,
	}
	err := Index(indexModel, constant.CNamePlayerDailyRecord)
	if err != nil {
		return err
	}
	return nil
}

func SetCNameAccountIndex() error {
	keysUnique := bson.D{
		{"openId", 1},
	}
	indexModelUnique := mongo.IndexModel{
		Keys:    keysUnique,                      // 1 表示升序，-1 表示降序
		Options: options.Index().SetUnique(true), // 设置索引选项，例如唯一索引
	}
	err := Unique(indexModelUnique, constant.CNameAccount)
	if err != nil {
		return err
	}
	return nil

}
