package services

import (
	"context"
	"log"

	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/db"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// EnsureWorkloadIndexes declares the indexes for the workload registry.
//
// It warns rather than being fatal, matching EnsureSecretIndexes and
// EnsureVulnIndexes: a missing index degrades these queries to a collection
// scan, which is no reason to refuse to serve the fleet.
func EnsureWorkloadIndexes() error {
	ctx := context.Background()

	idx := []mongo.IndexModel{
		{
			Keys:    bson.D{{Key: "instance_id", Value: 1}, {Key: "server_id", Value: 1}},
			Options: options.Index().SetUnique(true),
		},
		// Multikey, for the fleet-wide "which servers run image X" query, which
		// is the reason the snapshot is stored rather than fetched and discarded.
		{Keys: bson.D{{Key: "instance_id", Value: 1}, {Key: "workloads.image", Value: 1}}},
	}
	if _, err := db.Col("server_workloads").Indexes().CreateMany(ctx, idx); err != nil {
		log.Printf("warning: server_workloads indexes: %v", err)
	}
	return nil
}
