package main

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

	"github.com/acp/interceptor/internal/config"
	"github.com/acp/interceptor/internal/gateway"
)

func main() {
	cfg := config.Load()

	srv, err := gateway.NewServer(cfg)
	if err != nil {
		log.Fatalf("server init: %v", err)
	}

	go func() {
		log.Printf("interceptor listening on %s (OPA=%s path=%s policiesDir=%q)", cfg.HTTPAddr, cfg.OPABaseURL, cfg.OPADecisionPath, cfg.PoliciesDir)
		if err := srv.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("server stopped: %v", err)
		}
	}()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	<-stop

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Printf("graceful shutdown error: %v", err)
	}
}
