package server

import (
	"html/template"
	"net/http"
	"os"
	"strconv"
	"strings"

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

func buildNoteRows(notes []store.Note, lang i18n.Lang) []NoteRow {
	rows := make([]NoteRow, len(notes))
	index := map[int64]int{}
	for i, n := range notes {
		rows[i] = NoteRow{
			ID: n.ID, Author: n.Author, Body: n.Body, Path: n.FilePath,
			Start: n.LineStart, End: n.LineEnd, HasSuggestion: n.Suggestion != "",
			When: i18n.FormatDate(lang, n.CreatedAt), At: n.CreatedAt, ParentID: n.ParentID,
			HTML: template.HTML(markdown.Render(n.Body, "", "")),
		}
		index[n.ID] = i
	}
	for i := range rows {
		parent := rows[i].ParentID
		if parent == 0 {
			continue
		}
		pi, ok := index[parent]
		if !ok || rows[pi].ParentID != 0 {
			rows[i].ParentID = 0
			continue
		}
		rows[pi].Replies = append(rows[pi].Replies, rows[i])
	}
	return rows
}

func arrangeNotes(notes []store.Note, files []gitrepo.DiffFile, lang i18n.Lang) ([]NoteRow, []DiffFileView) {
	rows := buildNoteRows(notes, lang)
	placed := map[int64]bool{}
	var views []DiffFileView
	for _, f := range files {
		view := DiffFileView{Path: f.Path}
		for _, ln := range f.Lines {
			row := DiffLineView{Kind: ln.Kind, Text: ln.Text, Old: ln.Old, New: ln.New}
			if ln.New > 0 {
				for _, note := range rows {
					if note.ParentID != 0 {
						continue
					}
					if note.Path == f.Path && note.End == ln.New {
						row.Notes = append(row.Notes, note)
						placed[note.ID] = true
					}
				}
			}
			view.Lines = append(view.Lines, row)
		}
		views = append(views, view)
	}
	var general []NoteRow
	for _, note := range rows {
		if note.ParentID != 0 {
			continue
		}
		if note.Path == "" || !placed[note.ID] {
			general = append(general, note)
		}
	}
	return general, views
}

func repoPath(raw string) (string, bool) {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return "", true
	}
	p := strings.ReplaceAll(raw, `\`, "/")
	if strings.HasPrefix(p, "/") || strings.Contains(p, "..") || strings.ContainsAny(p, "\r\n") {
		return "", false
	}
	return p, true
}

func (s *Server) applySuggestions(w http.ResponseWriter, r *http.Request) {
	u, repo, role, ok := s.guard(w, r, access.RoleDeveloper)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	mr, err := s.mrFromRequest(r, repo.ID)
	if err != nil || mr.Status != "open" {
		http.NotFound(w, r)
		return
	}
	back := repoURL(repo) + "/-/merge-requests/" + strconv.FormatInt(mr.Number, 10)
	patterns, err := s.Store.ProtectedPatterns(r.Context(), repo.ID)
	if err != nil {
		s.redirect(w, r, back, "", s.trErr(r, err))
		return
	}
	if !role.CanPushBranch(access.BranchProtected(patterns, mr.SourceBranch)) {
		s.redirect(w, r, back, "", s.tr(r, "err.sugBranch", mr.SourceBranch))
		return
	}
	if s.StoragePath() == "" {
		s.redirect(w, r, back, "", s.tr(r, "err.noStorage"))
		return
	}
	title := strings.TrimSpace(r.FormValue("title"))
	if title == "" || strings.ContainsAny(title, "\r\n") {
		s.redirect(w, r, back, "", s.tr(r, "err.sugTitle"))
		return
	}
	notes, err := s.Store.ListNotes(r.Context(), mr.ID)
	if err != nil {
		s.redirect(w, r, back, "", s.trErr(r, err))
		return
	}
	byID := map[int64]store.Note{}
	for _, n := range notes {
		byID[n.ID] = n
	}
	var edits []gitrepo.SuggestionEdit
	seen := map[int64]bool{}
	for _, raw := range r.Form["id"] {
		id, err := strconv.ParseInt(raw, 10, 64)
		if err != nil || seen[id] {
			continue
		}
		seen[id] = true
		n, ok := byID[id]
		if !ok || n.Suggestion == "" || n.FilePath == "" {
			s.redirect(w, r, back, "", s.tr(r, "err.sugGone"))
			return
		}
		edits = append(edits, gitrepo.SuggestionEdit{
			Path: n.FilePath, Start: n.LineStart, End: n.LineEnd,
			Base: n.BaseText, Replacement: n.Suggestion,
		})
	}
	if len(edits) == 0 {
		s.redirect(w, r, back, "", s.tr(r, "err.sugEmpty"))
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	files := map[string]string{}
	for _, e := range edits {
		if _, ok := files[e.Path]; ok {
			continue
		}
		body, err := gitrepo.BlobText(r.Context(), s.Git, dir, mr.SourceBranch, e.Path)
		if err != nil {
			s.redirect(w, r, back, "", s.tr(r, "err.sugConflict", e.Path, e.Start, e.End))
			return
		}
		files[e.Path] = body
	}
	updated, err := gitrepo.ApplySuggestions(files, edits)
	if err != nil {
		s.redirect(w, r, back, "", s.trErr(r, err))
		return
	}
	branch := safeRev(mr.SourceBranch, "")
	if branch == "" {
		s.redirect(w, r, back, "", s.tr(r, "err.sugBranch", mr.SourceBranch))
		return
	}
	work, err := s.scratchDir("suggest")
	if err != nil {
		s.redirect(w, r, back, "", s.commitProblem(r, err))
		return
	}
	defer os.RemoveAll(work)
	email := u.Username + "@users.git.timfalken.com"
	if err := s.postReceive(r.Context(), repo, u, dir, func() error {
		return gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, title, r.FormValue("description"), updated, role, patterns)
	}); err != nil {
		s.redirect(w, r, back, "", s.commitProblem(r, err))
		return
	}
	s.redirect(w, r, back, s.tr(r, "flash.suggestions"), "")
}
