package main

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

	"gitea.hostxtra.co.uk/mrhid6/vantage/shared/mail"
	"gitea.hostxtra.co.uk/mrhid6/vantage/sitesvc/internal/api"
	"github.com/joho/godotenv"
)

func main() {

	godotenv.Load()

	addr := ":" + getEnv("PORT", "8082")

	sender := mail.FromEnv()
	contactTo := getEnv("SMTP_TO", "support@hostxtra.co.uk")
	if sender.Enabled() {
		log.Printf("smtp enabled (%s) contact form delivers to %s", sender.Host, contactTo)
	} else {
		log.Println("warning: SMTP_HOST/SMTP_FROM not set the contact form will refuse submissions")
	}

	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(sender, contactTo).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
}
