package server

import (
	"encoding/json"
	"net/http"
	"net/url"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/names"
)

func (s *Server) slugPreview(w http.ResponseWriter, r *http.Request) {
	u, ok := s.loginRequired(w, r)
	if !ok {
		return
	}
	kind := r.URL.Query().Get("kind")
	raw := r.URL.Query().Get("name")
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	slug, err := names.Slug(kind, raw)
	if strings.TrimSpace(raw) == "" || err != nil {
		_ = json.NewEncoder(w).Encode(map[string]string{"name": "", "url": ""})
		return
	}
	host := publicHost(s.Cfg.BaseURL, r.Host)
	var path string
	switch kind {
	case "repo":
		owner := s.previewOwner(r, u.ID, u.Username)
		path = host + "/" + owner + "/" + slug
	case "group":
		path = host + "/groups/" + slug
	default:
		_ = json.NewEncoder(w).Encode(map[string]string{"name": "", "url": ""})
		return
	}
	_ = json.NewEncoder(w).Encode(map[string]string{"name": slug, "url": path})
}

func (s *Server) previewOwner(r *http.Request, userID int64, username string) string {
	owner := strings.TrimSpace(r.URL.Query().Get("owner"))
	if owner == "" || owner == username {
		return username
	}
	g, err := s.Store.GroupByPath(r.Context(), owner)
	if err != nil {
		return username
	}
	role, err := s.Store.GroupRole(r.Context(), g.ID, userID)
	if err != nil || role == access.RoleNone {
		return username
	}
	return g.Path
}

func publicHost(base, fallback string) string {
	u, err := url.Parse(strings.TrimSpace(base))
	if err != nil || u.Host == "" {
		return fallback
	}
	return u.Host
}
