package main

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

	"service/internal/infrastructure/config"
	"service/internal/infrastructure/database"
	satuSehatFactory "service/internal/interfaces/satusehat"
	"service/internal/worker"
	"service/pkg/logger"
)

func main() {
	// 1. Load Configuration
	cfg := config.LoadConfig()

	// 2. Initialize Logger khusus untuk Worker
	loggerConfig := logger.Config{
		Level:        cfg.Logger.Level,
		Format:       cfg.Logger.Format,
		Output:       "both",
		ServiceName:  "service-worker", // Penanda log khusus worker
		EnableCaller: cfg.Server.Mode != "production",
		Environment:  cfg.Server.Mode,
	}
	logger.Init(loggerConfig)

	logger.Default().Info("Background Worker Microservice starting...",
		logger.String("environment", cfg.Server.Mode),
		logger.String("log_level", cfg.Logger.Level),
	)

	if err := cfg.Validate(); err != nil {
		logger.Default().Fatal("Config validation failed", logger.ErrorField(err))
	}

	// 3. Initialize Database Manager
	dbService := database.New(cfg)
	defer dbService.Close()

	// 4. Initialize SatuSehat Client (Dibutuhkan oleh worker manager)
	satusehatFact := satuSehatFactory.NewSatuSehatFactory(cfg.SatuSehat)
	satusehatClient := satusehatFact.Client()

	// 5. Setup Context untuk Graceful Shutdown
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 6. Initialize dan Jalankan Worker Manager
	workerManager := worker.NewManager(cfg, dbService, satusehatClient)
	workerManager.Start(ctx)

	// 7. Listener untuk OS Signals (Ctrl+C / SIGTERM)
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	<-quit // Block aplikasi sampai signal diterima
	logger.Default().Warn("Signal received, shutting down worker service...")
	cancel() // Batalkan context, trigger penghentian semua worker
}
