package mongo

import (
	"context"
	"fmt"

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

const collectionCommitAnalyses = "commit_analyses"

// EnsureIndexes creates required MongoDB indexes.
func (s *Store) EnsureIndexes(ctx context.Context) error {
	col := s.collection(collectionCommitAnalyses)

	_, err := col.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys:    bson.D{{Key: "analysis_id", Value: 1}},
		Options: options.Index().SetUnique(true),
	})
	if err != nil {
		return fmt.Errorf("create commit_analyses analysis_id index: %w", err)
	}

	_, err = col.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys: bson.D{
			{Key: "repo_id", Value: 1},
			{Key: "commit_sha", Value: 1},
		},
	})
	if err != nil {
		return fmt.Errorf("create commit_analyses repo commit index: %w", err)
	}

	_, err = col.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys:    bson.D{{Key: "event_id", Value: 1}},
		Options: options.Index().SetUnique(true).SetSparse(true),
	})
	if err != nil {
		return fmt.Errorf("create commit_analyses event_id index: %w", err)
	}

	_, err = col.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys: bson.D{
			{Key: "repo_id", Value: 1},
			{Key: "snapshot_id", Value: 1},
		},
	})
	if err != nil {
		return fmt.Errorf("create commit_analyses snapshot index: %w", err)
	}
	return nil
}
