package server

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

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

func (s *Server) pageURL(repo store.Repo, suffix string) string {
	if !strings.HasPrefix(suffix, "/") {
		suffix = "/" + suffix
	}
	return strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath() + suffix
}

func (s *Server) mrJSON(repo store.Repo, mr store.MergeRequest) map[string]any {
	return map[string]any{
		"id": mr.ID, "iid": mr.Number, "title": mr.Title, "description": mr.Description,
		"source_branch": mr.SourceBranch, "target_branch": mr.TargetBranch,
		"author": mr.Author, "state": mr.Status, "draft": mr.Draft, "labels": mr.Labels,
		"remove_source_branch": mr.RemoveSourceBranch, "squash": mr.Squash,
		"squash_commit_message": mr.SquashMessage,
		"web_url":               s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(mr.Number, 10)),
		"created_at":            rfcTime(mr.CreatedAt), "updated_at": rfcTime(mr.UpdatedAt),
	}
}

func (s *Server) apiMRs(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 {
			Title        string  `json:"title"`
			Description  string  `json:"description"`
			SourceBranch string  `json:"source_branch"`
			TargetBranch string  `json:"target_branch"`
			Draft        bool    `json:"draft"`
			Remove       *bool   `json:"remove_source_branch"`
			Squash       *bool   `json:"squash"`
			Message      *string `json:"squash_commit_message"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		mr, err := s.opCreateMR(r.Context(), apiUser(r), repo, body.Title, body.Description, body.SourceBranch, body.TargetBranch, body.Draft)
		if !s.apiOK(w, r, err) {
			return
		}
		remove, squash, message := true, false, ""
		if body.Remove != nil {
			remove = *body.Remove
		}
		if body.Squash != nil {
			squash = *body.Squash
		}
		if body.Message != nil {
			message = *body.Message
		}
		if err := s.Store.SetMergeOptions(r.Context(), mr.ID, remove, squash, message); !s.apiOK(w, r, err) {
			return
		}
		mr, err = s.Store.MergeRequestByNumber(r.Context(), repo.ID, mr.Number)
		if !s.apiOK(w, r, err) {
			return
		}
		writeJSON(w, http.StatusCreated, s.mrJSON(repo, mr))
		return
	}
	list, err := s.Store.ListMergeRequests(r.Context(), repo.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	// Optionele filters: state (open, merged, closed of all), source_branch, target_branch.
	q := r.URL.Query()
	wantState := strings.TrimSpace(q.Get("state"))
	wantSource := strings.TrimSpace(q.Get("source_branch"))
	wantTarget := strings.TrimSpace(q.Get("target_branch"))
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, mr := range list {
		if wantState != "" && wantState != "all" && mr.Status != wantState {
			continue
		}
		if wantSource != "" && mr.SourceBranch != wantSource {
			continue
		}
		if wantTarget != "" && mr.TargetBranch != wantTarget {
			continue
		}
		rows = append(rows, s.mrJSON(repo, mr))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiMR(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if r.Method == http.MethodPut {
		var body struct {
			Title       string  `json:"title"`
			Description string  `json:"description"`
			Labels      string  `json:"labels"`
			Remove      *bool   `json:"remove_source_branch"`
			Squash      *bool   `json:"squash"`
			Message     *string `json:"squash_commit_message"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		mr, err := s.opUpdateMR(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.Labels)
		if !s.apiOK(w, r, err) {
			return
		}
		if body.Remove != nil || body.Squash != nil || body.Message != nil {
			remove, squash, message := mr.RemoveSourceBranch, mr.Squash, mr.SquashMessage
			if body.Remove != nil {
				remove = *body.Remove
			}
			if body.Squash != nil {
				squash = *body.Squash
			}
			if body.Message != nil {
				message = *body.Message
			}
			if err := s.Store.SetMergeOptions(r.Context(), mr.ID, remove, squash, message); !s.apiOK(w, r, err) {
				return
			}
			mr, err = s.Store.MergeRequestByNumber(r.Context(), repo.ID, mr.Number)
			if !s.apiOK(w, r, err) {
				return
			}
		}
		writeJSON(w, http.StatusOK, s.mrJSON(repo, mr))
		return
	}
	mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
	if err != nil {
		s.writeAPIErr(w, r, notFound(err))
		return
	}
	writeJSON(w, http.StatusOK, s.mrJSON(repo, mr))
}

func (s *Server) apiMRNotes(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if r.Method == http.MethodGet {
		mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
		if err != nil {
			s.writeAPIErr(w, r, notFound(err))
			return
		}
		notes, err := s.Store.ListNotes(r.Context(), mr.ID)
		if !s.apiOK(w, r, err) {
			return
		}
		rows := make([]map[string]any, 0, len(notes))
		for _, note := range notes {
			rows = append(rows, map[string]any{
				"id": note.ID, "body": note.Body, "author": note.Author,
				"file_path": note.FilePath, "line_start": note.LineStart, "line_end": note.LineEnd,
				"suggestion": note.Suggestion, "parent_id": note.ParentID, "created_at": rfcTime(note.CreatedAt),
			})
		}
		page, per := pageQuery(r)
		writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
		return
	}
	var body struct {
		Body      string `json:"body"`
		Path      string `json:"path"`
		LineStart int    `json:"line_start"`
		LineEnd   int    `json:"line_end"`
		ParentID  int64  `json:"parent_id"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	note, err := s.opAddNote(r, apiUser(r), repo, n, body.Body, body.Path, body.LineStart, body.LineEnd, body.ParentID)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"id": note.ID})
}

func (s *Server) apiReview(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	var body struct {
		Status string `json:"status"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opReview(r.Context(), apiUser(r), repo, n, body.Status)) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"status": body.Status})
}

func (s *Server) apiDismissReview(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	var body struct {
		UserID int64 `json:"user_id"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opDismissReview(r.Context(), apiUser(r), repo, n, body.UserID)) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"status": "dismissed"})
}

func (s *Server) apiSuggestions(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	var body struct {
		Title       string  `json:"title"`
		Description string  `json:"description"`
		IDs         []int64 `json:"ids"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opApplySuggestions(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.IDs)) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"applied": len(body.IDs)})
}

func (s *Server) apiMerge(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	var body struct {
		Remove  *bool   `json:"remove_source_branch"`
		Squash  *bool   `json:"squash"`
		Message *string `json:"squash_commit_message"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	out, err := s.opMergeMR(r, apiUser(r), repo, n, mergeChoice{Remove: body.Remove, Squash: body.Squash, Message: body.Message})
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"state": "merged", "source_branch_removed": out.Removed, "source_branch_skip": out.Skip,
		"web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(n, 10)),
	})
}

func (s *Server) apiCloseMR(w http.ResponseWriter, r *http.Request) {
	s.apiSetMR(w, r, false)
}

func (s *Server) apiReopenMR(w http.ResponseWriter, r *http.Request) {
	s.apiSetMR(w, r, true)
}

func (s *Server) apiSetMR(w http.ResponseWriter, r *http.Request, reopen bool) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if !s.apiOK(w, r, s.opCloseMR(r.Context(), apiUser(r), repo, n, reopen)) {
		return
	}
	state := "closed"
	if reopen {
		state = "open"
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"state": state, "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(n, 10)),
	})
}

func (s *Server) pipeJSON(repo store.Repo, p store.Pipeline) map[string]any {
	return map[string]any{
		"id": p.ID, "sha": p.CommitSHA, "ref": p.Ref, "status": s.pipeStatusFor(p), "source": p.Source,
		"actor": p.Actor, "created_at": rfcTime(p.CreatedAt), "started_at": rfcTime(p.StartedAt), "finished_at": rfcTime(p.FinishedAt),
		"web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(p.ID, 10)),
	}
}

// pipeJSONJobs is pipeJSON met cancel_reason en display_status, die de
// jobs nodig hebben. status blijft canceled voor oude clients.
func (s *Server) pipeJSONJobs(ctx context.Context, repo store.Repo, p store.Pipeline) map[string]any {
	out := s.pipeJSON(repo, p)
	st := s.pipeStatusFor(p)
	out["display_status"] = st
	out["cancel_reason"] = nil
	out["waiting_for"] = nil
	if blk, ok := s.protectedBlocker(p); ok && st == "waiting_for_job" {
		out["waiting_for"] = map[string]any{"job_id": blk.ID, "job_name": blk.Name, "pipeline_id": blk.PipelineID}
	}
	if st == "canceled" {
		jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
		out["cancel_reason"] = "manual"
		if store.PipelineObsolete(jobs) {
			out["cancel_reason"] = "superseded"
			out["display_status"] = "obsolete"
		}
	}
	return out
}

func (s *Server) jobJSON(ctx context.Context, j store.Job) map[string]any {
	out := map[string]any{
		"id": j.ID, "name": j.Name, "stage": j.Stage, "status": j.Status, "when": j.When,
		"allow_failure": j.AllowFailure, "started_at": rfcTime(j.StartedAt), "finished_at": rfcTime(j.FinishedAt),
		"runner": nil, "do_not_interrupt": j.DoNotInterrupt, "display_status": j.Status, "cancel_reason": nil, "failure_reason": nil,
	}
	if r := j.CancelReason(); r != "" {
		out["cancel_reason"] = r
		if j.Obsolete() {
			out["display_status"] = "obsolete"
		}
	}
	if r := j.FailureReason(); r != "" {
		out["failure_reason"] = r
	}
	if jr := s.Store.JobRun(ctx, j.ID); jr.RunnerName != "" {
		kind := "builtin"
		if jr.RunnerID > 0 {
			kind = "remote"
		}
		out["runner"] = map[string]any{"id": jr.RunnerID, "name": jr.RunnerName, "kind": kind}
	}
	return out
}

func (s *Server) apiPipelines(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 {
			Ref string `json:"ref"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		id, err := s.opRunPipeline(r.Context(), apiUser(r), repo, body.Ref, "api")
		if !s.apiOK(w, r, err) {
			return
		}
		if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil {
			writeJSON(w, http.StatusCreated, s.pipeJSON(repo, p))
			return
		}
		writeJSON(w, http.StatusCreated, map[string]any{
			"id": id, "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)),
		})
		return
	}
	f, err := s.pipelineFilter(r, repo)
	if !s.apiOK(w, r, err) {
		return
	}
	list, err := s.Store.FindPipelines(r.Context(), repo.ID, f)
	if !s.apiOK(w, r, err) {
		return
	}
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, p := range list {
		rows = append(rows, s.pipeJSONJobs(r.Context(), repo, p))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiPipeline(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
	if err != nil {
		s.writeAPIErr(w, r, notFound(err))
		return
	}
	writeJSON(w, http.StatusOK, s.pipeJSONJobs(r.Context(), repo, p))
}

func (s *Server) apiRetryPipeline(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	pipeID, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	var body struct {
		Mode string `json:"mode"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	body.Mode = retryPipelineMode(body.Mode)
	id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode)
	if !s.apiOK(w, r, err) {
		return
	}
	p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
	if err != nil {
		s.writeAPIErr(w, r, notFound(err))
		return
	}
	code := http.StatusOK
	if body.Mode == "all" {
		code = http.StatusCreated
	}
	writeJSON(w, code, s.pipeJSON(repo, p))
}

func (s *Server) apiCancelPipeline(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	if !s.apiOK(w, r, s.opCancelPipeline(r.Context(), apiUser(r), repo, id, forceParam(r))) {
		return
	}
	if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil {
		writeJSON(w, http.StatusOK, s.pipeJSON(repo, p))
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"id": id, "status": "canceled", "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)),
	})
}

func (s *Server) apiJobs(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return
	}
	p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
	if err != nil {
		s.writeAPIErr(w, r, notFound(err))
		return
	}
	jobs, err := s.Store.JobsByPipeline(r.Context(), p.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	rows := make([]map[string]any, 0, len(jobs))
	for _, j := range jobs {
		rows = append(rows, s.jobJSON(r.Context(), j))
	}
	writeJSON(w, http.StatusOK, rows)
}

func (s *Server) apiJob(w http.ResponseWriter, r *http.Request) {
	_, job, ok := s.apiFindJob(w, r)
	if !ok {
		return
	}
	writeJSON(w, http.StatusOK, s.jobJSON(r.Context(), job))
}

func (s *Server) apiJobLog(w http.ResponseWriter, r *http.Request) {
	_, job, ok := s.apiFindJob(w, r)
	if !ok {
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(job.Log))
}

func (s *Server) apiJobAction(w http.ResponseWriter, r *http.Request, action string) {
	repo, p, job, ok := s.apiFindJobFull(w, r, access.RoleDeveloper)
	if !ok {
		return
	}
	updated, err := s.opJobActionForce(r.Context(), apiUser(r), repo, p.ID, job.ID, action, action == "cancel" && forceParam(r))
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, s.jobJSON(r.Context(), updated))
}

func (s *Server) apiPlayJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "play") }
func (s *Server) apiRetryJob(w http.ResponseWriter, r *http.Request) {
	s.apiJobAction(w, r, "retry")
}
func (s *Server) apiCancelJob(w http.ResponseWriter, r *http.Request) {
	s.apiJobAction(w, r, "cancel")
}

func (s *Server) apiFindJob(w http.ResponseWriter, r *http.Request) (store.Pipeline, store.Job, bool) {
	_, p, job, ok := s.apiFindJobFull(w, r, access.RoleReadonly)
	return p, job, ok
}

func (s *Server) apiFindJobFull(w http.ResponseWriter, r *http.Request, min access.Role) (store.Repo, store.Pipeline, store.Job, bool) {
	repo, _, ok := s.apiRepo(w, r, min)
	if !ok {
		return store.Repo{}, store.Pipeline{}, store.Job{}, false
	}
	pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Repo{}, store.Pipeline{}, store.Job{}, false
	}
	jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64)
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Repo{}, store.Pipeline{}, store.Job{}, false
	}
	p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid)
	if err != nil {
		s.writeAPIErr(w, r, notFound(err))
		return store.Repo{}, store.Pipeline{}, store.Job{}, false
	}
	jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
	for _, j := range jobs {
		if j.ID == jid {
			return repo, p, j, true
		}
	}
	s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
	return store.Repo{}, store.Pipeline{}, store.Job{}, false
}

func (s *Server) apiArtifacts(w http.ResponseWriter, r *http.Request) {
	_, job, ok := s.apiFindJob(w, r)
	if !ok {
		return
	}
	list, err := s.Store.ListArtifacts(r.Context(), job.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	rows := make([]map[string]any, 0, len(list))
	for _, a := range list {
		rows = append(rows, map[string]any{"path": a.Path, "size": a.Size})
	}
	writeJSON(w, http.StatusOK, rows)
}

func (s *Server) apiArtifact(w http.ResponseWriter, r *http.Request) {
	_, job, ok := s.apiFindJob(w, r)
	if !ok {
		return
	}
	want := r.PathValue("path")
	if strings.Contains(want, "..") {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))
		return
	}
	list, err := s.Store.ListArtifacts(r.Context(), job.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	for _, a := range list {
		if a.Path == want {
			http.ServeFile(w, r, a.StoragePath)
			return
		}
	}
	s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
}

func (s *Server) apiCIFile(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	if r.Method == http.MethodPut {
		var body struct {
			Branch  string `json:"branch"`
			Base    string `json:"base"`
			Message string `json:"message"`
			Content string `json:"content"`
			OpenMR  bool   `json:"open_mr"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		sha, number, err := s.opSaveCI(r.Context(), apiUser(r), repo, body.Base, body.Branch, body.Message, body.Content, body.OpenMR)
		if !s.apiOK(w, r, err) {
			return
		}
		writeJSON(w, http.StatusOK, map[string]any{"id": sha, "merge_request": number})
		return
	}
	body, err := s.opCIFile(r.Context(), repo, r.URL.Query().Get("ref"))
	if !s.apiOK(w, r, err) {
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(body))
}

func (s *Server) apiLintCI(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	var body struct {
		Body string `json:"body"`
		Ref  string `json:"ref"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	out, err := s.opLintCI(r, repo, body.Body, body.Ref)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, out)
}

func (s *Server) apiPresets(w http.ResponseWriter, r *http.Request) {
	set, err := images.Effective(s.Cfg.CI.ImageOverrides())
	if err != nil {
		s.writeAPIErr(w, r, fail(500, err))
		return
	}
	rows := make([]map[string]any, 0, len(set))
	for _, p := range set {
		rows = append(rows, map[string]any{"name": "bluegit/" + p.Name, "from": p.From, "runtime": p.Runtime, "tools": p.Tools, "direct": p.Direct})
	}
	writeJSON(w, http.StatusOK, rows)
}

func (s *Server) apiReleases(w http.ResponseWriter, r *http.Request) {
	repo, role, ok := s.apiRepoReleases(w, r)
	if !ok {
		return
	}
	list, err := s.Store.ListReleases(r.Context(), repo.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, rel := range list {
		assets := make([]map[string]any, 0, len(rel.Assets))
		for _, a := range rel.Assets {
			assets = append(assets, map[string]any{"name": a.Name, "size": a.Size})
		}
		row := map[string]any{
			"id": rel.ID, "tag": rel.Tag, "commit": rel.CommitSHA, "name": rel.Name, "body": rel.Body,
			"created_at": rfcTime(rel.CreatedAt), "assets": assets,
		}
		if releaseOnly(repo, role) {
			delete(row, "commit") // geen verwijzing naar broncode voor niet-leden
		}
		rows = append(rows, row)
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiReleaseAsset(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepoReleases(w, r)
	if !ok {
		return
	}
	rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
	if err != nil {
		s.writeAPIErr(w, r, notFound(err))
		return
	}
	name := r.PathValue("name")
	for _, a := range rel.Assets {
		if a.Name == name {
			w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
			http.ServeFile(w, r, a.StoragePath)
			return
		}
	}
	s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
}

// pipelineFilter leest sha, ref en mr uit de query.
// ref mag een branchnaam zijn (refs/heads/ en refs/tags/ worden geprobeerd)
// of een volledige ref. mr is het MR-nummer: pipelines van die MR plus
// pushes naar de bronbranch.
func (s *Server) pipelineFilter(r *http.Request, repo store.Repo) (store.PipelineFilter, error) {
	q := r.URL.Query()
	var f store.PipelineFilter
	if sha := strings.TrimSpace(q.Get("sha")); sha != "" {
		if len(sha) < 7 || len(sha) > 40 || strings.Trim(strings.ToLower(sha), "0123456789abcdef") != "" {
			return f, fail(400, i18n.E("err.badSHA"))
		}
		f.SHA = sha
	}
	if ref := strings.TrimSpace(q.Get("ref")); ref != "" {
		if strings.HasPrefix(ref, "refs/") {
			f.Refs = []string{ref}
		} else {
			f.Refs = []string{"refs/heads/" + ref, "refs/tags/" + ref}
		}
	}
	if raw := strings.TrimSpace(q.Get("mr")); raw != "" {
		n, err := strconv.ParseInt(raw, 10, 64)
		if err != nil || n < 1 {
			return f, fail(400, i18n.E("err.notFound"))
		}
		mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
		if err != nil {
			return f, notFound(err)
		}
		if len(f.Refs) > 0 {
			return f, fail(400, i18n.E("err.pipeFilter"))
		}
		f.MRID = mr.ID
		f.Refs = []string{"refs/heads/" + mr.SourceBranch}
	}
	return f, nil
}
