package server

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

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

type slugBody struct {
	Name      string `json:"name"`
	URL       string `json:"url"`
	Available bool   `json:"available"`
}

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(slugBody{})
		return
	}
	host := publicHost(s.Cfg.BaseURL, r.Host)
	var path string
	ownerKind, ownerID := "user", u.ID
	switch kind {
	case "repo":
		ownerKind, ownerID, path = s.previewOwnerRef(r, u)
		path = host + "/" + path + "/" + slug
	case "group":
		path = host + "/groups/" + slug
	default:
		_ = json.NewEncoder(w).Encode(slugBody{})
		return
	}
	taken, err := s.Store.SlugTaken(r.Context(), kind, slug, ownerKind, ownerID)
	_ = json.NewEncoder(w).Encode(slugBody{Name: slug, URL: path, Available: err == nil && !taken})
}

func (s *Server) previewOwnerRef(r *http.Request, u store.User) (string, int64, string) {
	path := s.previewOwner(r, u.ID, u.Username)
	if path == u.Username {
		return "user", u.ID, path
	}
	g, err := s.Store.GroupByPath(r.Context(), path)
	if err != nil {
		return "user", u.ID, u.Username
	}
	return "group", g.ID, g.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
}
