package helpers

import (
	"encoding/json"
	"log"
	"net"
	"net/http"
	"os"
	"sort"

	"tea.chunkbyte.com/kato/go-worm/lib/models"
)

var Log = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lmicroseconds)

func RecoverHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if recovered := recover(); recovered != nil {
				Log.Printf("panic %s %s: %v", r.Method, r.URL.Path, recovered)
				WriteError(w, http.StatusInternalServerError, "internal server error")
			}
		}()
		next.ServeHTTP(w, r)
	})
}

func WriteJSON(w http.ResponseWriter, status int, value any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(value); err != nil {
		Log.Printf("write response: %v", err)
	}
}

func WriteError(w http.ResponseWriter, status int, message string) {
	WriteJSON(w, status, models.APIError{Error: message})
}

func Username() string {
	user := os.Getenv("USERNAME")
	if user == "" {
		user = os.Getenv("USER")
	}
	return user
}

func LocalIPs() []string {
	interfaces, err := net.Interfaces()
	if err != nil {
		return nil
	}
	var ips []string
	for _, iface := range interfaces {
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			continue
		}
		addresses, _ := iface.Addrs()
		for _, address := range addresses {
			ip, _, err := net.ParseCIDR(address.String())
			if err == nil && ip != nil {
				ips = append(ips, ip.String())
			}
		}
	}
	sort.Strings(ips)
	return ips
}
