package main

import (
	"context"
	"log/slog"
	"os"
	"os/signal"
	"syscall"

	"aigateway.local/core/internal/platform/cache"
	"aigateway.local/core/internal/platform/config"
	"aigateway.local/core/internal/platform/cryptox"
	"aigateway.local/core/internal/platform/database"
	platformid "aigateway.local/core/internal/platform/id"
	"aigateway.local/core/internal/workbench"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
	cfg, err := config.Load()
	if err != nil {
		logger.Error("invalid configuration", "error", err)
		os.Exit(1)
	}
	if cfg.Database.URL == "" || cfg.Redis.CriticalURL == "" {
		logger.Error("DATABASE_URL and REDIS_CRITICAL_URL are required")
		os.Exit(1)
	}
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	db, err := database.Open(ctx, cfg.Database)
	if err != nil {
		logger.Error("database initialization failed", "error", err)
		os.Exit(1)
	}
	defer db.Close()
	client, err := cache.Open(cfg.Redis.CriticalURL)
	if err != nil {
		logger.Error("redis initialization failed", "error", err)
		os.Exit(1)
	}
	defer client.Close()
	cipher, err := cryptox.NewKeyring(cfg.Credentials.MasterKey, cfg.Credentials.KEKVersion, cfg.Credentials.KEKKeyring, "notification-signing-secret")
	if err != nil {
		logger.Error("notification cipher initialization failed", "error", err)
		os.Exit(1)
	}
	consumer, err := platformid.NewUUID()
	if err != nil {
		logger.Error("consumer ID generation failed", "error", err)
		os.Exit(1)
	}
	service := workbench.NewNotificationService(workbench.NewService(db), cipher, cfg.Credentials.AllowPrivateWebhookURL)
	dispatcher := workbench.NewNotificationDispatcher(service, client, cfg.Outbox.Stream, "notification-"+consumer, logger)
	logger.Info("notification worker started", "consumer", consumer, "stream", cfg.Outbox.Stream)
	if err = dispatcher.Run(ctx); err != nil {
		logger.Error("notification worker stopped unexpectedly", "error", err)
		os.Exit(1)
	}
	logger.Info("notification worker stopped", "consumer", consumer)
}
