package main

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

	"github.com/joho/godotenv"
	"github.com/mrhid6/vantage/sitesvc/internal/api"
	"github.com/mrhid6/vantage/sitesvc/internal/mail"
	"github.com/mrhid6/vantage/sitesvc/internal/store"
)

func main() {

	godotenv.Load()

	mongoURI := getEnv("MONGO_URI", "mongodb://localhost:27017/vantage")
	addr := ":" + getEnv("PORT", "8082")

	if err := store.Connect(mongoURI); err != nil {
		log.Fatalf("failed to connect to MongoDB: %v", err)
	}
	log.Printf("connected to MongoDB (database %q)", store.DatabaseName())

	guardCtx, guardCancel := context.WithTimeout(context.Background(), 10*time.Second)
	guardErr := store.RequireMigratedDatabase(guardCtx)
	guardCancel()
	if guardErr != nil {
		log.Fatalf("database check failed: %v", guardErr)
	}

	if err := store.EnsureIndexes(); err != nil {
		log.Fatalf("failed to ensure indexes: %v", err)
	}

	mailCfg := mail.FromEnv()
	if mailCfg.Enabled() {
		log.Printf("smtp enabled (%s) contact form delivers to %s", mailCfg.Host, mailCfg.To)
	} else {
		log.Println("warning: SMTP_HOST/SMTP_FROM not set the contact and signup forms will refuse submissions")
	}

	if os.Getenv("PUBLIC_URL") == "" {
		log.Println("warning: PUBLIC_URL is unset verification links will be relative and will not work")
	}
	if os.Getenv("SITE_ORIGIN") == "" {
		log.Println("warning: SITE_ORIGIN is unset cross-origin browser requests will be refused")
	}

	srv := &http.Server{
		Addr:              addr,
		Handler:           api.New(mailCfg).Routes(),
		ReadHeaderTimeout: 10 * time.Second,
		ReadTimeout:       20 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	go func() {
		log.Printf("sitesvc listening on %s", addr)
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("server error: %v", err)
		}
	}()

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	<-ctx.Done()

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Printf("shutdown: %v", err)
	}
	log.Println("sitesvc stopped")
}

func getEnv(key, fallback string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return fallback
}
