package main

import (
	"log/slog"
	"net/http"
	"os"

	_ "github.com/lib/pq"

	"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
	"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
	"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
	"mgit.msbls.de/m/KanzlAI-mGMT/internal/logging"
	"mgit.msbls.de/m/KanzlAI-mGMT/internal/router"
	"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)

func main() {
	logging.Setup()

	cfg, err := config.Load()
	if err != nil {
		slog.Error("failed to load config", "error", err)
		os.Exit(1)
	}

	database, err := db.Connect(cfg.DatabaseURL)
	if err != nil {
		slog.Error("failed to connect to database", "error", err)
		os.Exit(1)
	}
	defer database.Close()

	authMW := auth.NewMiddleware(cfg.SupabaseJWTSecret, database)

	// Start CalDAV sync service
	calDAVSvc := services.NewCalDAVService(database)
	calDAVSvc.Start()
	defer calDAVSvc.Stop()

	// Start notification reminder service
	notifSvc := services.NewNotificationService(database)
	notifSvc.Start()
	defer notifSvc.Stop()

	handler := router.New(database, authMW, cfg, calDAVSvc, notifSvc, database)

	slog.Info("starting KanzlAI API server", "port", cfg.Port)
	if err := http.ListenAndServe(":"+cfg.Port, handler); err != nil {
		slog.Error("server failed", "error", err)
		os.Exit(1)
	}
}
