package repositoryimp

import (
	"context"

	ri "github.com/tech/sendico/pkg/db/repository/index"
	"github.com/tech/sendico/pkg/merrors"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func (r *MongoRepository) CreateIndex(def *ri.Definition) error {
	if r.collection == nil {
		return merrors.NoData("data collection is not set")
	}
	if len(def.Keys) == 0 {
		return merrors.InvalidArgument("Index definition has no keys", "index.keys")
	}

	// ----- build BSON keys --------------------------------------------------
	keys := bson.D{}
	for _, k := range def.Keys {
		var value any
		switch {
		case k.Type != "":
			value = k.Type // text, 2dsphere, …
		case k.Sort == ri.Desc:
			value = int8(-1)
		default:
			value = int8(1) // default to Asc
		}
		keys = append(keys, bson.E{Key: k.Field, Value: value})
	}

	opts := options.Index().
		SetUnique(def.Unique)
	if def.TTL != nil {
		opts.SetExpireAfterSeconds(*def.TTL)
	}
	if def.Name != "" {
		opts.SetName(def.Name)
	}
	if def.PartialFilter != nil {
		opts.SetPartialFilterExpression(def.PartialFilter.BuildQuery())
	}
	if def.Sparse {
		opts.SetSparse(def.Sparse)
	}

	_, err := r.collection.Indexes().CreateOne(
		context.Background(),
		mongo.IndexModel{Keys: keys, Options: opts},
	)
	return err
}
