package server

import (
	"net/http"
	"strings"

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

func (s *Server) gitHTTP(w http.ResponseWriter, r *http.Request) {
	if s.StoragePath() == "" {
		http.Error(w, s.noStorageText(r), http.StatusServiceUnavailable)
		return
	}
	owner := r.PathValue("owner")
	repoSeg := r.PathValue("repo")
	if !strings.HasSuffix(repoSeg, ".git") {
		http.NotFound(w, r)
		return
	}
	name := strings.TrimSuffix(repoSeg, ".git")
	repo, err := s.Store.RepoByPath(r.Context(), owner, name)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	service := r.URL.Query().Get("service")
	write := service == "git-receive-pack" || strings.HasSuffix(r.URL.Path, "/git-receive-pack")
	user, scopes, authed := s.gitUser(r)
	var role access.Role
	if authed {
		role, err = s.Store.EffectiveRole(r.Context(), user.ID, repo.ID)
		if err != nil {
			http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
			return
		}
	}
	if write {
		if !authed {
			s.askAuth(w)
			return
		}
		if !scopes.RepoWrite() {
			http.Error(w, s.tr(r, "err.apiScope"), http.StatusForbidden)
			return
		}
		if !role.CanWriteCode() {
			http.Error(w, s.tr(r, "err.noWrite"), http.StatusForbidden)
			return
		}
	} else if !role.CanRead() && repo.Visibility != "public" {
		if !authed {
			s.askAuth(w)
			return
		}
		http.Error(w, s.tr(r, "err.noRead"), http.StatusForbidden)
		return
	} else if authed && !scopes.RepoRead() {
		http.Error(w, s.tr(r, "err.apiScope"), http.StatusForbidden)
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	var before map[string]string
	var extra []string
	if write {
		before, _ = gitrepo.Refs(r.Context(), s.Git, dir)
		patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
		tagPatterns, _ := s.Store.ProtectedTagPatterns(r.Context(), repo.ID)
		extra = gitrepo.PushEnv(role, patterns, tagPatterns)
	}
	rest := strings.TrimPrefix(r.URL.Path, "/"+owner+"/"+repoSeg)
	pathInfo := gitrepo.PathInfo(owner, repoSeg, rest)
	if err := gitrepo.ServeSmartHTTP(w, r, s.Git, gitrepo.ProjectRoot(s.StoragePath()), pathInfo, extra); err != nil && s.Log != nil {
		s.Log.Error("git http", "err", err, "path", r.URL.Path)
	}
	if write {
		after, err := gitrepo.Refs(r.Context(), s.Git, dir)
		if err == nil {
			s.AfterPush(repo, user, before, after)
		}
	}
}

func (s *Server) gitUser(r *http.Request) (store.User, access.Scopes, bool) {
	_, pass, ok := r.BasicAuth()
	if !ok {
		h := r.Header.Get("Authorization")
		if strings.HasPrefix(strings.ToLower(h), "bearer ") {
			pass = strings.TrimSpace(h[7:])
			ok = pass != ""
		}
	}
	if !ok || !strings.HasPrefix(pass, "bg_") {
		return store.User{}, access.Scopes{}, false
	}
	auth, err := s.Store.AuthenticateToken(r.Context(), pass)
	if err != nil {
		return store.User{}, access.Scopes{}, false
	}
	return auth.User, access.StoredScopes(auth.Token.Scopes), true
}

func (s *Server) askAuth(w http.ResponseWriter) {
	w.Header().Set("WWW-Authenticate", `Basic realm="BlueGit"`)
	http.Error(w, "aanmelden met een toegangstoken als wachtwoord", http.StatusUnauthorized)
}
