package server

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

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

// decodeBranch maakt een branchnaam uit een pad of een bevestiging.
// ServeMux decodeert %2F één keer. Een client die de slash nóg een keer
// encodeert (%252F) levert anders cursor%2F… en de bevestiging wijkt af.
func decodeBranch(raw string) string {
	name := strings.TrimSpace(raw)
	for i := 0; i < 3; i++ {
		next, err := url.PathUnescape(name)
		if err != nil || next == name {
			return name
		}
		name = next
	}
	return name
}

// pathWildcard leest een ServeMux-wildcard. De mux matcht op de escaped path
// (EscapedPath/RawPath), zodat zowel feature/x als feature%2Fx bij {name...}
// horen. PathValue laat %2F ongecodeerd; decodeBranch maakt daar een taknaam van.
func pathWildcard(r *http.Request, key string) string {
	return decodeBranch(r.PathValue(key))
}

func (s *Server) repoRole(ctx context.Context, user store.User, repo store.Repo) (access.Role, error) {
	role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
	if err != nil {
		return "", fail(500, err)
	}
	return role, nil
}

func (s *Server) opCreateBranch(ctx context.Context, user store.User, repo store.Repo, name, from string) error {
	role, err := s.repoRole(ctx, user, repo)
	if err != nil {
		return err
	}
	if !role.CanWriteCode() {
		return fail(403, i18n.E("err.forbidden"))
	}
	name = strings.TrimSpace(name)
	if err := names.ValidBranch(name); err != nil {
		return fail(400, err)
	}
	from = safeRev(from, repo.DefaultBranch)
	if from == "" {
		return fail(400, i18n.E("err.branches"))
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+name) != "" {
		return fail(400, i18n.E("err.branchName", name))
	}
	if err := s.postReceive(ctx, repo, user, dir, func() error {
		return gitrepo.CreateBranch(ctx, s.Git, dir, name, from)
	}); err != nil {
		return fail(400, err)
	}
	return nil
}

func (s *Server) branchLockError(ctx context.Context, repo store.Repo, name string) error {
	if name == repo.DefaultBranch {
		return i18n.E("err.branchLocked", name)
	}
	patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
	if access.BranchProtected(patterns, name) {
		return i18n.E("err.branchLocked", name)
	}
	return nil
}

func (s *Server) opDeleteBranch(ctx context.Context, user store.User, repo store.Repo, name, confirm string) error {
	role, err := s.repoRole(ctx, user, repo)
	if err != nil {
		return err
	}
	if !role.CanWriteCode() {
		return fail(403, i18n.E("err.forbidden"))
	}
	name = decodeBranch(name)
	confirm = decodeBranch(confirm)
	if confirm != name || name == "" {
		return fail(400, i18n.E("err.branchConfirm"))
	}
	if err := s.branchLockError(ctx, repo, name); err != nil {
		return fail(400, err)
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if err := s.postReceive(ctx, repo, user, dir, func() error {
		return gitrepo.DeleteBranch(ctx, s.Git, dir, name)
	}); err != nil {
		return fail(400, err)
	}
	return nil
}

func (s *Server) opRenameBranch(ctx context.Context, user store.User, repo store.Repo, name, newName, confirm string) error {
	role, err := s.repoRole(ctx, user, repo)
	if err != nil {
		return err
	}
	if !role.CanWriteCode() {
		return fail(403, i18n.E("err.forbidden"))
	}
	name = decodeBranch(name)
	newName = decodeBranch(newName)
	confirm = decodeBranch(confirm)
	if confirm != name || name == "" {
		return fail(400, i18n.E("err.branchConfirm"))
	}
	if err := names.ValidBranch(newName); err != nil {
		return fail(400, err)
	}
	if err := s.branchLockError(ctx, repo, name); err != nil {
		return fail(400, err)
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+newName) != "" {
		return fail(400, i18n.E("err.branchName", newName))
	}
	if err := s.postReceive(ctx, repo, user, dir, func() error {
		if err := gitrepo.RenameBranch(ctx, s.Git, dir, name, newName); err != nil {
			return err
		}
		return s.Store.RenameOpenMRBranches(ctx, repo.ID, name, newName)
	}); err != nil {
		return fail(400, err)
	}
	return nil
}

func (s *Server) opCreateTag(ctx context.Context, user store.User, repo store.Repo, name, target, message string) error {
	role, err := s.repoRole(ctx, user, repo)
	if err != nil {
		return err
	}
	if !role.CanWriteCode() {
		return fail(403, i18n.E("err.forbidden"))
	}
	name = strings.TrimSpace(name)
	if err := names.ValidTag(name); err != nil {
		return fail(400, err)
	}
	patterns, _ := s.Store.ProtectedTagPatterns(ctx, repo.ID)
	if access.BranchProtected(patterns, name) && !role.CanManageSettings() {
		return fail(403, i18n.E("err.tagProtected", name))
	}
	if strings.TrimSpace(target) == "" {
		target = repo.DefaultBranch
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if err := s.postReceive(ctx, repo, user, dir, func() error {
		return gitrepo.CreateTag(ctx, s.Git, dir, name, target, message, user.Username, userEmail(user.Username))
	}); err != nil {
		return fail(400, err)
	}
	return nil
}

func (s *Server) opDeleteTag(ctx context.Context, user store.User, repo store.Repo, name string) error {
	role, err := s.repoRole(ctx, user, repo)
	if err != nil {
		return err
	}
	if !role.CanWriteCode() {
		return fail(403, i18n.E("err.forbidden"))
	}
	name = strings.TrimSpace(name)
	patterns, _ := s.Store.ProtectedTagPatterns(ctx, repo.ID)
	if access.BranchProtected(patterns, name) && !role.CanManageSettings() {
		return fail(403, i18n.E("err.tagProtected", name))
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if err := gitrepo.DeleteTag(ctx, s.Git, dir, name); err != nil {
		return fail(400, err)
	}
	s.refsChanged(repo)
	return nil
}

type fileAction struct {
	Action  string `json:"action"`
	Path    string `json:"file_path"`
	Content string `json:"content"`
}

func (s *Server) opWriteFiles(ctx context.Context, user store.User, repo store.Repo, role access.Role, branch, base, title, description string, files map[string]string, deletes []string) (string, error) {
	if role == "" {
		var err error
		role, err = s.repoRole(ctx, user, repo)
		if err != nil {
			return "", err
		}
	}
	if !role.CanWriteCode() {
		return "", fail(403, i18n.E("err.forbidden"))
	}
	branch = strings.TrimSpace(branch)
	if !validBranchName(branch) {
		return "", fail(400, i18n.E("edit.badBranch"))
	}
	title = strings.TrimSpace(title)
	if title == "" || strings.ContainsAny(title, "\r\n") {
		return "", fail(400, i18n.E("edit.needMessage"))
	}
	if base == "" {
		base = repo.DefaultBranch
	}
	patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
	if access.BranchProtected(patterns, branch) && !role.CanPushBranch(true) {
		return "", fail(403, i18n.E("edit.protected"))
	}
	if s.StoragePath() == "" {
		return "", fail(503, i18n.E("err.noStorage"))
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	work, err := s.scratchDir("api-commit")
	if err != nil {
		return "", fail(500, err)
	}
	defer os.RemoveAll(work)
	if err := s.ensureBranch(ctx, dir, branch, base, work); err != nil {
		return "", fail(400, err)
	}
	if err := s.postReceive(ctx, repo, user, dir, func() error {
		return gitrepo.CommitChanges(ctx, s.Git, dir, work, branch, user.Username, userEmail(user.Username), title, description, files, deletes, role, patterns)
	}); err != nil {
		return "", fail(400, err)
	}
	return gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "refs/heads/"+branch), nil
}

func (s *Server) opCommitActions(ctx context.Context, user store.User, repo store.Repo, branch, base, title, description string, actions []fileAction) (string, error) {
	files := map[string]string{}
	var deletes []string
	for _, a := range actions {
		path, ok := repoPath(a.Path)
		if !ok || path == "" {
			return "", fail(400, i18n.E("err.sugFile"))
		}
		switch a.Action {
		case "", "create", "update":
			files[path] = a.Content
		case "delete":
			deletes = append(deletes, path)
		default:
			return "", fail(400, i18n.E("err.sugFile"))
		}
	}
	return s.opWriteFiles(ctx, user, repo, "", branch, base, title, description, files, deletes)
}
