package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"mind/internal/config"
	"mind/internal/db"
	httpapi "mind/internal/http"
	"mind/internal/logx"
	"mind/internal/glue"
)

func main() {
	cfg := config.Load()
	logger := logx.New()

	database, err := db.OpenAndMigrate(cfg)
	if err != nil {
		log.Fatalf("db init: %v", err)
	}
	repo := db.NewRepo(database)

	g := glue.NewGlue(repo, cfg)
	r := httpapi.NewRouter(logger, cfg, g)

	srv := &http.Server{ 
		Addr:         ":" + cfg.Port,
		Handler:      r,
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 60 * time.Second,
	}

	go func() {
		logger.Infof("MIND v0 listening on :%s", cfg.Port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Errorf("server error: %v", err)
		}
	}()

	// graceful shutdown
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_ = srv.Shutdown(ctx)
}
