package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"abuse_registration_poc/internal/auth"
	"abuse_registration_poc/internal/config"
	"abuse_registration_poc/internal/handlers"
	"abuse_registration_poc/internal/routes"
	"abuse_registration_poc/internal/store"
)

var Version = "dev"

func main() {
	releaseVersion := flag.Bool("version", false, "show binary version and shut down programme")
	portOverride := flag.String("port", "", "override api.port from config (e.g. ':8080')")
	envOverride := flag.String("env", "", "override environment from config (e.g. 'prod', 'dev')")
	flag.Parse()

	if *releaseVersion {
		fmt.Printf("version matching git tag and branch: %s", Version)
		os.Exit(0)
	}

	cfg := config.LoadConfig()
	if *portOverride != "" {
		log.Printf("Overriding api.port from config (%s) with flag value (%s)", cfg.API.Port, *portOverride)
		cfg.API.Port = *portOverride
	}
	if *envOverride != "" {
		log.Printf("Overriding environment from config (%s) with flag value (%s)", cfg.Environment, *envOverride)
		cfg.Environment = *envOverride
	}
	config.SetAPIKey(cfg.Auth.JWTSecret)

	registrationStore := store.NewMemoryStore(cfg.Dataset.Size, cfg.Dataset.ResetInterval)
	userStore := auth.NewStaticUserStore()

	h, err := handlers.New(handlers.Dependencies{
		Store:   registrationStore,
		Users:   userStore,
		Version: Version,
		AppName: cfg.API.Name,
		BaseURL: cfg.API.BaseURL,
	})
	if err != nil {
		log.Fatalf("Failed to initialize handlers: %v", err)
	}

	server := &http.Server{
		Addr:              cfg.API.Port,
		Handler:           routes.RegisterRoutes(h),
		ReadHeaderTimeout: 5 * time.Second,
	}

	log.Printf("starting go api on port %s", cfg.API.Port)
	time.Sleep(100 * time.Millisecond)
	if err := server.ListenAndServe(); err != nil {
		log.Fatalf("ERROR: Failed to start server: %v", err)
	}
}
