package hub

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/netip"
	"strings"
)

func (app *App) render(name string, w http.ResponseWriter, data any) error {
	tmpl, ok := app.tmpl[name]
	if !ok {
		log.Printf("Template not found: %s", name)
		return errors.New("not found")
	}
	if err := tmpl.Execute(w, data); err != nil {
		log.Printf("Failed to render template %s: %v", name, err)
	}
	return nil
}

func (app *App) redirect(w http.ResponseWriter, r *http.Request, url string, args ...any) error {
	if len(args) > 0 {
		url = fmt.Sprintf(url, args...)
	}
	http.Redirect(w, r, url, http.StatusSeeOther)
	return nil
}

func (app *App) sendJSON(w http.ResponseWriter, data any) error {
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(data); err != nil {
		log.Printf("Failed to send JSON: %v", err)
	}
	return nil
}

func stringToIP(in string) ([]byte, error) {
	in = strings.TrimSpace(in)
	if len(in) == 0 {
		return []byte{}, nil
	}

	addr, err := netip.ParseAddr(in)
	if err != nil {
		return nil, err
	}
	return addr.AsSlice(), nil
}

func ipBytesTostring(in []byte) string {
	if addr, ok := netip.AddrFromSlice(in); ok {
		return addr.String()
	}
	return ""
}
