package server

import (
	"context"
	"net/http"
	"os"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/state"
)

const noStorageMsg = "Opslag is nog niet ingesteld. De beheerder kiest een pad in de webinterface.\n"

func allowsWithoutStorage(r *http.Request) bool {
	switch r.URL.Path {
	case "/healthz", "/login", "/auth/callback", "/logout", "/setup":
		return true
	}
	return strings.HasPrefix(r.URL.Path, "/assets/")
}

func isGitPath(path string) bool {
	return strings.HasSuffix(path, "/info/refs") ||
		strings.HasSuffix(path, "/git-upload-pack") ||
		strings.HasSuffix(path, "/git-receive-pack")
}

func (s *Server) gate(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if allowsWithoutStorage(r) || s.StoragePath() != "" {
			next.ServeHTTP(w, r)
			return
		}
		if isGitPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/api/") {
			http.Error(w, noStorageMsg, http.StatusServiceUnavailable)
			return
		}
		if p := s.who(r); p.OK && p.User.InstanceAdmin {
			http.Redirect(w, r, "/setup", http.StatusFound)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// StoragePath is de datadisk. Leeg zolang de beheerder er geen heeft gekozen.
func (s *Server) StoragePath() string {
	s.storageMu.RLock()
	set, path := s.storageSet, s.storage
	s.storageMu.RUnlock()
	if set {
		return path
	}
	s.storageMu.Lock()
	defer s.storageMu.Unlock()
	if !s.storageSet {
		s.storage = s.Cfg.StoragePath
		s.storageSet = true
	}
	return s.storage
}

// AdoptStorage zet het pad dat bij het starten al geldig was.
func (s *Server) AdoptStorage(path string) {
	s.storageMu.Lock()
	s.storage = path
	s.storageSet = true
	s.storageMu.Unlock()
	if path != "" && s.AfterStorage != nil {
		s.AfterStorage(path)
	}
}

func (s *Server) setupPage(w http.ResponseWriter, r *http.Request) {
	if _, ok := s.adminOnly(w, r); !ok {
		return
	}
	s.renderSetup(w, r, "", "")
}

func (s *Server) setupSave(w http.ResponseWriter, r *http.Request) {
	if _, ok := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
		return
	}
	if s.StateDir == "" {
		s.renderSetup(w, r, "Het pad kon niet bewaard worden.", r.FormValue("path"))
		return
	}
	info, err := state.Inspect(r.FormValue("path"))
	if err != nil {
		s.renderSetup(w, r, err.Error(), strings.TrimSpace(r.FormValue("path")))
		return
	}
	if same, err := samePath(s.StateDir, info.Path); err != nil {
		s.renderSetup(w, r, err.Error(), info.Path)
		return
	} else if same {
		s.renderSetup(w, r, "Kies de map voor de repositories.", info.Path)
		return
	}
	previous := s.StoragePath()
	if err := state.Write(s.StateDir, info.Path); err != nil {
		s.renderSetup(w, r, err.Error(), info.Path)
		return
	}
	s.AdoptStorage(info.Path)
	s.RefreshHooks()
	notice := "Opslag ingesteld op " + info.Path + ". " + state.Format(info.Free) + " vrij."
	if previous != "" && previous != info.Path {
		notice = "Opslagpad gewijzigd naar " + info.Path + ". Bestaande data is niet verplaatst. " + state.Format(info.Free) + " vrij."
	}
	s.redirect(w, r, "/", notice, "")
}

func samePath(stateDir, path string) (bool, error) {
	if stateDir == "" {
		return false, nil
	}
	return strings.TrimRight(stateDir, "/") == strings.TrimRight(path, "/"), nil
}

func (s *Server) adminOnly(w http.ResponseWriter, r *http.Request) (bool, bool) {
	u, ok := s.loginRequired(w, r)
	if !ok {
		return false, false
	}
	if !u.InstanceAdmin {
		http.Error(w, "Je mag de opslag niet instellen.", http.StatusForbidden)
		return false, false
	}
	return true, true
}

func (s *Server) renderSetup(w http.ResponseWriter, r *http.Request, problem, prefill string) {
	v := s.view(w, r, "Opslag")
	if problem != "" {
		v.Err = problem
	}
	v.MinFree = state.Format(state.MinFreeBytes)
	v.StoragePath = strings.TrimSpace(prefill)
	if v.StoragePath == "" {
		v.StoragePath = s.StoragePath()
	}
	if v.StoragePath == "" && s.StateDir != "" {
		if saved, err := state.Read(s.StateDir); err == nil {
			v.StoragePath = saved
		}
	}
	if v.StoragePath != "" {
		info, err := state.Inspect(v.StoragePath)
		if info.Total > 0 {
			v.StorageFree = state.Format(info.Free)
			v.StorageTotal = state.Format(info.Total)
		}
		if err != nil && v.Err == "" {
			v.Err = err.Error()
		}
	}
	s.render(w, "setup", v)
}

// RefreshHooks zet de pre-receive-hook opnieuw in elke repository die op de datadisk staat.
func (s *Server) RefreshHooks() {
	root := s.StoragePath()
	if root == "" || s.HookBin == "" || s.Store == nil {
		return
	}
	repos, err := s.Store.AllRepos(context.Background())
	if err != nil {
		return
	}
	for _, repo := range repos {
		dir := gitrepo.Dir(root, repo.OwnerPath, repo.Name)
		if _, err := os.Stat(dir); err != nil {
			continue
		}
		if err := gitrepo.InstallHook(dir, s.HookBin); err != nil && s.Log != nil {
			s.Log.Error("hook", "repo", repo.FullPath(), "err", err)
		}
	}
}
