package main

import (
	"context"
	"flag"
	"fmt"
	"time"

	"apps/backend/internal/config"

	"github.com/zeromicro/go-zero/core/conf"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// init creates idempotent operational indexes only. It intentionally never
// inserts members or other business records.
func main() {
	configFile := flag.String("f", "etc/gateway.yaml", "config file")
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	c.ApplyEnv()
	if c.Mongo.URI == "" || c.Mongo.Database == "" {
		panic("Mongo.URI and Mongo.Database are required")
	}

	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(c.Mongo.URI))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(context.Background())

	db := client.Database(c.Mongo.Database)
	indexes := map[string][]mongo.IndexModel{
		"jobs": {
			{Keys: bson.D{{Key: "status", Value: 1}, {Key: "run_after", Value: 1}, {Key: "created_at", Value: 1}}, Options: options.Index().SetName("claim_due_jobs")},
			{Keys: bson.D{{Key: "status", Value: 1}, {Key: "completed_at", Value: 1}}, Options: options.Index().SetName("purge_terminal_jobs")},
		},
		"studio_outbox": {
			{Keys: bson.D{{Key: "status", Value: 1}, {Key: "updated_at", Value: 1}}, Options: options.Index().SetName("worker_outbox_status_updated")},
			{Keys: bson.D{{Key: "steps.status", Value: 1}, {Key: "steps.scheduled_at", Value: 1}, {Key: "steps.lease_expires_at", Value: 1}}, Options: options.Index().SetName("claim_due_outbox_steps")},
			{Keys: bson.D{{Key: "owner_uid", Value: 1}, {Key: "updated_at", Value: -1}}, Options: options.Index().SetName("owner_outbox_updated")},
		},
	}
	for collection, models := range indexes {
		if _, err := db.Collection(collection).Indexes().CreateMany(ctx, models); err != nil {
			panic(fmt.Errorf("create %s indexes: %w", collection, err))
		}
	}
	fmt.Println("database indexes initialized")
}
