package main

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

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

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()
	redisClient, err := cache.Open(cfg.Redis.CriticalURL)
	if err != nil {
		logger.Error("redis initialization failed", "error", err)
		os.Exit(1)
	}
	defer redisClient.Close()
	if err := db.Ping(ctx); err != nil {
		logger.Error("database is unavailable", "error", err)
		os.Exit(1)
	}
	if err := redisClient.Ping(ctx).Err(); err != nil {
		logger.Error("redis is unavailable", "error", err)
		os.Exit(1)
	}
	workerID, err := platformid.NewUUID()
	if err != nil {
		logger.Error("worker ID generation failed", "error", err)
		os.Exit(1)
	}
	workerID = "outbox-" + workerID
	worker := outbox.NewWorker(
		outbox.NewStore(db),
		outbox.NewRedisPublisher(redisClient, cfg.Outbox.Stream, cfg.Outbox.StreamMaxLength, cfg.Outbox.MarkerTTL),
		outbox.WorkerConfig{WorkerID: workerID, BatchSize: cfg.Outbox.BatchSize, PollInterval: cfg.Outbox.PollInterval, Lease: cfg.Outbox.Lease, MaxAttempts: cfg.Outbox.MaxAttempts, MaxBackoff: cfg.Outbox.MaxBackoff},
		logger,
	)
	logger.Info("outbox worker started", "worker_id", workerID, "stream", cfg.Outbox.Stream)
	if err := worker.Run(ctx); err != nil {
		logger.Error("outbox worker stopped unexpectedly", "error", err)
		os.Exit(1)
	}
	logger.Info("outbox worker stopped", "worker_id", workerID)
}
