package config

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

	"gitea.miguelmuniz.com/rogueking/junk2jive-server/internal/logger"
	"gitea.miguelmuniz.com/rogueking/junk2jive-server/internal/router"
	"github.com/joho/godotenv"
)

var AllowedOrigins []string

type Flags struct {
	Port int
}

func LoadEnv(filePath string) {
	if err := godotenv.Load(filePath); err != nil {
		logger.Fatal("Error loading .env file")
	}
}

func DeclareFlags() *Flags {
	// env := flag.String("e", "development", "Set the environment ( development | production )")
	port := flag.Int("p", 0, "Set the port that will be used")

	flag.Parse()

	return &Flags{
		Port: *port,
	}
}

func ConfigPort(flags *Flags) string {
	var port string
	if flags.Port != 0 {
		port = fmt.Sprintf(":%d", flags.Port)
	} else {
		if os.Getenv("APP_PORT") == "" {
			logger.Warn("No port specified, default port :80 used...")
			return ":80"
		}
		port = fmt.Sprintf(":%s", os.Getenv("APP_PORT"))
	}
	return port
}

func SetupServer(port string, router *router.Router, flags *Flags) *http.Server {
	var server *http.Server

    server = &http.Server{
        Addr:    port,
        Handler: router.GetRouter(),
    }

    return server
}
