package serra

import (
	"context"

	"github.com/spf13/cobra"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

func init() {
	rootCmd.AddCommand(initializeCmd)
}

var initializeCmd = &cobra.Command{
	Use: "init",
	Short: "Initialize database",
	Long: "Create database optimization structures",
	SilenceErrors: true,
	RunE: func(cmd *cobra.Command, _ []string) error {
		return initializeDatabase()
	},
}

func initializeDatabase() error {
	client := storageConnect()
	l := Logger()
	defer storageDisconnect(client)

	// create sets collection
	client.Database("serra").Collection("sets")

	// create total collection and insert entry if it doesn't exist
	totalcoll := &Collection{client.Database("serra").Collection("total")}
	totalcoll.InsertOne(context.TODO(), Total{ID: "1", Value: []PriceEntry{}})

	cardscoll := &Collection{client.Database("serra").Collection("cards")}

	fieldsToIndex := []string{ "name", "prices.eur", "prices.usd", "collectornumber", "serra_created" }
	for _, fieldName := range fieldsToIndex {
		if createIndex(cardscoll, fieldName) != nil {
			l.Warnf("Failed to create index on field '%s'", fieldName)
		}
	}

	return nil
}

func createIndex(coll *Collection, fieldName string) error {
	indexModel := mongo.IndexModel{
		Keys: bson.D{{fieldName, 1}},
	}

	_, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
	return err
}
