package server

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

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

func (s *Server) apiBranches(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if r.Method == http.MethodGet {
		tips, err := gitrepo.BranchTips(r.Context(), s.Git, dir)
		if err != nil {
			tips = nil
		}
		page, per := pageQuery(r)
		rows := make([]map[string]any, 0, len(tips))
		for _, t := range tips {
			rows = append(rows, map[string]any{
				"name": t.Name, "commit": t.SHA, "subject": t.Subject, "date": t.Date,
				"default": t.Name == repo.DefaultBranch,
			})
		}
		writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
		return
	}
	var body struct {
		Name string `json:"name"`
		From string `json:"from"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opCreateBranch(r.Context(), apiUser(r), repo, body.Name, body.From)) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"name": body.Name})
}

func (s *Server) apiBranch(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	name := r.PathValue("branch")
	if r.Method == http.MethodDelete {
		var body struct {
			Confirm string `json:"confirm"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		if !s.apiOK(w, r, s.opDeleteBranch(r.Context(), apiUser(r), repo, name, body.Confirm)) {
			return
		}
		writeJSON(w, http.StatusNoContent, nil)
		return
	}
	var body struct {
		Name    string `json:"name"`
		Confirm string `json:"confirm"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opRenameBranch(r.Context(), apiUser(r), repo, name, body.Name, body.Confirm)) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"name": body.Name})
}

func (s *Server) apiTags(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if r.Method == http.MethodGet {
		names, err := gitrepo.Tags(r.Context(), s.Git, dir)
		if err != nil {
			names = nil
		}
		if names == nil {
			names = []string{}
		}
		page, per := pageQuery(r)
		writePage(w, r, slicePage(names, page, per), len(names), page, per)
		return
	}
	var in struct {
		Name    string `json:"name"`
		Target  string `json:"target"`
		Message string `json:"message"`
	}
	if err := readJSON(r, &in); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opCreateTag(r.Context(), apiUser(r), repo, in.Name, in.Target, in.Message)) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"name": in.Name})
}

func (s *Server) apiDeleteTag(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	if !s.apiOK(w, r, s.opDeleteTag(r.Context(), apiUser(r), repo, r.PathValue("tag"))) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiTagArchive(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	name := r.PathValue("tag")
	format := r.URL.Query().Get("format")
	if format == "" {
		format = "tar.gz"
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if !gitrepo.HasTag(r.Context(), s.Git, dir, name) {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	filename := archiveFilename(repo.Name, name, format)
	if format == "zip" {
		w.Header().Set("Content-Type", "application/zip")
	} else {
		w.Header().Set("Content-Type", "application/gzip")
	}
	w.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
	if err := gitrepo.Archive(r.Context(), w, s.Git, dir, repo.Name+"-"+strings.ReplaceAll(name, "/", "-"), name, format); err != nil {
		s.writeAPIErr(w, r, fail(400, err))
	}
}

func (s *Server) apiTree(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	ref := safeRev(r.URL.Query().Get("ref"), repo.DefaultBranch)
	rel := strings.Trim(r.URL.Query().Get("path"), "/")
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	entries, err := gitrepo.Tree(r.Context(), s.Git, dir, ref, rel)
	if err != nil {
		writeJSON(w, http.StatusOK, []any{})
		return
	}
	rows := make([]map[string]any, 0, len(entries))
	for _, e := range entries {
		rows = append(rows, map[string]any{"name": e.Name, "type": e.Type, "mode": e.Mode, "id": e.SHA})
	}
	page, per := pageQuery(r)
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiFile(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	path, pathOK := repoPath(r.PathValue("path"))
	if !pathOK || path == "" {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))
		return
	}
	ref := safeRev(r.URL.Query().Get("ref"), repo.DefaultBranch)
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	out, err := exec.CommandContext(r.Context(), s.Git, "-C", dir, "show", ref+":"+path).Output()
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if strings.Contains(string(out), "\x00") {
		w.Header().Set("Content-Type", "application/octet-stream")
	} else {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	}
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(out)
}

func (s *Server) apiCommits(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	if r.Method == http.MethodPost {
		var body struct {
			Branch        string       `json:"branch"`
			StartBranch   string       `json:"start_branch"`
			CommitMessage string       `json:"commit_message"`
			Actions       []fileAction `json:"actions"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		sha, err := s.opCommitActions(r.Context(), apiUser(r), repo, body.Branch, body.StartBranch, body.CommitMessage, "", body.Actions)
		if !s.apiOK(w, r, err) {
			return
		}
		writeJSON(w, http.StatusCreated, map[string]any{"id": sha, "branch": body.Branch})
		return
	}
	ref := safeRev(r.URL.Query().Get("ref"), repo.DefaultBranch)
	page, per := pageQuery(r)
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	limit := page * per
	if limit > 200 {
		limit = 200
	}
	list, err := gitrepo.Log(r.Context(), s.Git, dir, ref, limit)
	if err != nil || list == nil {
		list = nil
	}
	rows := make([]map[string]any, 0, len(list))
	for _, c := range list {
		rows = append(rows, commitJSON(c))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func commitJSON(c gitrepo.Commit) map[string]any {
	return map[string]any{
		"id": c.SHA, "short_id": c.Short, "title": c.Subject, "message": c.Body,
		"author_name": c.Author, "author_email": c.Email, "authored_date": c.Date,
	}
}

func (s *Server) apiCommit(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	sha := r.PathValue("sha")
	if !safeSHA(sha) {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	c, err := gitrepo.Show(r.Context(), s.Git, dir, sha)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	writeJSON(w, http.StatusOK, commitJSON(c))
}

func (s *Server) apiCommitDiff(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	sha := r.PathValue("sha")
	if !safeSHA(sha) {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	parents, files, err := gitrepo.CommitPatch(r.Context(), s.Git, dir, sha)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	out := make([]map[string]any, 0, len(files))
	for _, f := range files {
		var b strings.Builder
		for _, ln := range f.Lines {
			b.WriteString(ln.Kind)
			b.WriteString(ln.Text)
			b.WriteByte('\n')
		}
		out = append(out, map[string]any{
			"status": f.Status, "path": f.Path, "old_path": f.OldPath,
			"added": f.Added, "deleted": f.Deleted, "binary": f.Binary, "diff": b.String(),
		})
	}
	if parents == nil {
		parents = []string{}
	}
	writeJSON(w, http.StatusOK, map[string]any{"id": sha, "parents": parents, "files": out})
}
