package main

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

	"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
	"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/server"
)

func main() {
	ctx := context.Background()
	ctx, cancle := context.WithCancel(ctx)
	defer cancle()

	go func() {
		sigint := make(chan os.Signal, 1)
		signal.Notify(sigint, os.Interrupt)
		<-sigint

		cancle()
	}()

	slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})))

	cfg, err := config.Read(ctx)
	if err != nil {
		slog.Error("could not read configuaration", "err", err)
	}

	setupLogger(&cfg)

	err = server.Start(ctx, cfg)
	if err != nil {
		slog.Error("error while serving", "err", err)
		return
	}
}

func setupLogger(cfg *config.Cfg) {
	opts := slog.HandlerOptions{
		Level: cfg.LogLevel,
	}
	var handler slog.Handler

	if cfg.LogJSON {
		handler = slog.NewJSONHandler(os.Stdout, &opts)
	} else {
		handler = slog.NewTextHandler(os.Stdout, &opts)
	}

	slog.SetDefault(
		slog.New(
			handler,
		),
	)
}
