package main

import (
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/joho/godotenv"
	"github.com/rede5/gohorsejobs/backend/docs"
	"github.com/rede5/gohorsejobs/backend/internal/database"
	"github.com/rede5/gohorsejobs/backend/internal/router"
)

// @title           GoHorseJobs API
// @version         1.0
// @description     API for GoHorseJobs recruitment platform.
// @BasePath        /
func main() {
	// Load .env file
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found or error loading it")
	}

	// Validate JWT_SECRET strength (must be at least 32 characters / 256 bits)
	jwtSecret := os.Getenv("JWT_SECRET")
	if jwtSecret == "" || len(jwtSecret) < 32 {
		log.Println("⚠️  WARNING: JWT_SECRET is empty or too short (< 32 chars). Use a strong secret in production!")
		if os.Getenv("ENV") == "production" {
			log.Fatal("FATAL: Cannot start in production without strong JWT_SECRET")
		}
	}

	database.InitDB()
	database.RunMigrations()

	// Configure Swagger Host dynamically
	apiHost := os.Getenv("BACKEND_HOST")
	if apiHost == "" {
		apiHost = "localhost:8521"
	}

	// Detect scheme from env var
	schemes := []string{"http", "https"} // default to both
	if strings.HasPrefix(apiHost, "https://") {
		schemes = []string{"https"}
	} else if strings.HasPrefix(apiHost, "http://") {
		schemes = []string{"http"}
	}

	// Strip protocol schemes to ensure clean host for Swagger
	apiHost = strings.TrimPrefix(apiHost, "http://")
	apiHost = strings.TrimPrefix(apiHost, "https://")

	docs.SwaggerInfo.Host = apiHost
	docs.SwaggerInfo.Schemes = schemes

	handler := router.NewRouter()

	port := os.Getenv("BACKEND_PORT")
	if port == "" {
		port = "8521"
	}

	log.Println("Starting server on :" + port)
	log.Println("API Host configured to:", apiHost)

	if err := http.ListenAndServe(":"+port, handler); err != nil {
		log.Fatalf("Server failed to start: %v", err)
	}
}
