package config

import (
	"log/slog"
	"os"
	"strconv"
)

type Config struct {
	DatabaseURL string
	JWTSecret   string
	JWTIssuer   string
	InstanceID  string
	Port        uint16
}

const (
	// minSecretLength enforces the OWASP JWT Cheat Sheet recommendation of
	// at least 64 characters for HMAC secrets to resist offline brute-force.
	minSecretLength = 64

	// devSecret is used only when JWT_SECRET is unset. 74 chars, clearly marked
	// as insecure; production deployments must override via env var.
	devSecret = "dev-only-secret-DO-NOT-USE-IN-PRODUCTION-please-set-JWT_SECRET-env-var-now"
)

func FromEnv() Config {
	port := uint16(8080)
	if p, err := strconv.ParseUint(os.Getenv("PORT"), 10, 16); err == nil {
		port = uint16(p)
	}

	jwtSecret := os.Getenv("JWT_SECRET")
	switch {
	case jwtSecret == "":
		slog.Warn("JWT_SECRET not set — using insecure development default; never deploy without setting JWT_SECRET")
		jwtSecret = devSecret
	case len(jwtSecret) < minSecretLength:
		slog.Error("JWT_SECRET too short — OWASP requires HMAC secrets >= 64 chars to resist offline cracking",
			"length", len(jwtSecret), "required", minSecretLength)
		os.Exit(1)
	}

	issuer := os.Getenv("JWT_ISSUER")
	if issuer == "" {
		issuer = "forumz"
	}

	instanceID := os.Getenv("INSTANCE_ID")
	if instanceID == "" {
		instanceID = "dev"
	}

	return Config{
		DatabaseURL: os.Getenv("DATABASE_URL"),
		JWTSecret:   jwtSecret,
		JWTIssuer:   issuer,
		InstanceID:  instanceID,
		Port:        port,
	}
}
