package server

import (
	"net/http"
	"strconv"

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

func groupJSON(g store.Group) map[string]any {
	return map[string]any{
		"id": g.ID, "name": g.Name, "path": g.Path, "description": g.Description,
		"visibility": g.Visibility, "default_role": g.DefaultRole,
	}
}

func projectJSON(repo store.Repo) map[string]any {
	return map[string]any{
		"id": repo.ID, "path": repo.FullPath(), "name": repo.Name, "owner": repo.OwnerPath,
		"description": repo.Description, "visibility": repo.Visibility, "default_branch": repo.DefaultBranch,
		"release_visibility": repo.ReleaseVisibility, "ci_paused": repo.CIPaused,
	}
}

func memberJSON(m store.Member) map[string]any {
	return map[string]any{"user_id": m.UserID, "username": m.Username, "role": m.Role, "pending": m.Pending}
}

func (s *Server) apiListGroups(w http.ResponseWriter, r *http.Request) {
	list, err := s.Store.ListGroups(r.Context(), apiUser(r).ID)
	if !s.apiOK(w, r, err) {
		return
	}
	if r.URL.Query().Get("sort") == "pushed" {
		if at, err := s.Store.GroupPushTimes(r.Context()); err == nil {
			store.SortGroupsByPush(list, at)
		}
	}
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, g := range list {
		rows = append(rows, groupJSON(g))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiCreateGroup(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Name        string `json:"name"`
		Description string `json:"description"`
		DefaultRole string `json:"default_role"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	g, err := s.opCreateGroup(r.Context(), apiUser(r), body.Name, body.Description, body.DefaultRole)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusCreated, groupJSON(g))
}

func (s *Server) apiGroup(w http.ResponseWriter, r *http.Request, min access.Role) (store.Group, bool) {
	g, err := s.Store.GroupByPath(r.Context(), r.PathValue("path"))
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Group{}, false
	}
	role, err := s.Store.GroupRole(r.Context(), g.ID, apiUser(r).ID)
	if err != nil {
		s.writeAPIErr(w, r, fail(500, err))
		return store.Group{}, false
	}
	if !role.CanRead() && g.Visibility != "public" {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Group{}, false
	}
	if min != access.RoleNone && min != access.RoleReadonly && !role.AtLeast(min) {
		s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
		return store.Group{}, false
	}
	if min == access.RoleReadonly && !role.CanRead() && g.Visibility != "public" {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Group{}, false
	}
	return g, true
}

func (s *Server) apiGetGroup(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	writeJSON(w, http.StatusOK, groupJSON(g))
}

func (s *Server) apiPutGroup(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	var body struct {
		Description string `json:"description"`
		Visibility  string `json:"visibility"`
		DefaultRole string `json:"default_role"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opUpdateGroup(r.Context(), apiUser(r), g, body.Description, body.Visibility, body.DefaultRole)) {
		return
	}
	g, _ = s.Store.GroupByPath(r.Context(), g.Path)
	writeJSON(w, http.StatusOK, groupJSON(g))
}

func (s *Server) apiDeleteGroup(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	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.opDeleteGroup(r.Context(), apiUser(r), g, body.Confirm)) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiTransferGroup(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	var body struct {
		Username string `json:"username"`
		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.opTransferGroup(r.Context(), apiUser(r), g, body.Username, body.Confirm)) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"path": g.Path, "owner": body.Username})
}

func (s *Server) apiGroupProjects(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	list, err := s.Store.ReposByGroup(r.Context(), g.ID)
	if !s.apiOK(w, r, err) {
		return
	}
	s.writeProjects(w, r, list)
}

func (s *Server) apiListProjects(w http.ResponseWriter, r *http.Request) {
	ids, err := s.Store.ListRepoIDs(r.Context(), apiUser(r).ID)
	if !s.apiOK(w, r, err) {
		return
	}
	list, err := s.Store.ReposByIDs(r.Context(), ids)
	if !s.apiOK(w, r, err) {
		return
	}
	if r.URL.Query().Get("sort") == "pushed" {
		store.SortReposByPush(list)
	}
	s.writeProjects(w, r, list)
}

func (s *Server) writeProjects(w http.ResponseWriter, r *http.Request, list []store.Repo) {
	page, per := pageQuery(r)
	rows := make([]map[string]any, 0, len(list))
	for _, repo := range list {
		rows = append(rows, projectJSON(repo))
	}
	writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
}

func (s *Server) apiCreateProject(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Name        string `json:"name"`
		Description string `json:"description"`
		Group       string `json:"group"`
		Visibility  string `json:"visibility"`
		Readme      bool   `json:"initialize_with_readme"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	repo, err := s.opCreateRepo(r.Context(), apiUser(r), body.Name, body.Description, body.Group, body.Visibility, body.Readme)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusCreated, projectJSON(repo))
}

func (s *Server) apiRepo(w http.ResponseWriter, r *http.Request, min access.Role) (store.Repo, access.Role, bool) {
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Repo{}, "", false
	}
	role, err := s.Store.EffectiveRole(r.Context(), apiUser(r).ID, repo.ID)
	if err != nil {
		s.writeAPIErr(w, r, fail(500, err))
		return store.Repo{}, "", false
	}
	if jr := jobRole(r, repo.ID); jr != access.RoleNone && !role.CanRead() {
		role = jr
	}
	readable := role.CanRead() || repo.Visibility == "public"
	if !readable {
		s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
		return store.Repo{}, "", false
	}
	if min.Rank() > access.RoleReadonly.Rank() && !role.AtLeast(min) {
		s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
		return store.Repo{}, "", false
	}
	return repo, role, true
}

func (s *Server) apiGetProject(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	writeJSON(w, http.StatusOK, s.projectJSONFull(r, repo))
}

func (s *Server) apiPutProject(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	var body struct {
		Description       *string `json:"description"`
		Visibility        *string `json:"visibility"`
		ReleaseVisibility *string `json:"release_visibility"`
		StaleManualDays   *int    `json:"stale_manual_days"`
		DefaultBranch     *string `json:"default_branch"`
		CIPaused          *bool   `json:"ci_paused"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	// Velden die ontbreken blijven zoals ze zijn.
	desc, vis := repo.Description, repo.Visibility
	if body.Description != nil {
		desc = *body.Description
	}
	if body.Visibility != nil {
		vis = *body.Visibility
	}
	if body.ReleaseVisibility != nil && !store.ValidReleaseVisibility(*body.ReleaseVisibility) {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.releaseVisibility")))
		return
	}
	if body.StaleManualDays != nil && (*body.StaleManualDays < -1 || *body.StaleManualDays > 3650) {
		s.writeAPIErr(w, r, fail(400, i18n.E("stale.err.days")))
		return
	}
	if !s.apiOK(w, r, s.opUpdateRepo(r.Context(), apiUser(r), repo, desc, vis)) {
		return
	}
	if body.ReleaseVisibility != nil {
		if !s.apiOK(w, r, s.opSetReleaseVisibility(r.Context(), apiUser(r), repo, *body.ReleaseVisibility)) {
			return
		}
	}
	if body.StaleManualDays != nil {
		if !s.apiOK(w, r, s.Store.SetRepoStaleManualDays(r.Context(), repo.ID, *body.StaleManualDays)) {
			return
		}
	}
	if body.DefaultBranch != nil {
		if !s.apiOK(w, r, s.opSetDefaultBranch(r.Context(), apiUser(r), repo, *body.DefaultBranch)) {
			return
		}
	}
	if body.CIPaused != nil {
		if !s.apiOK(w, r, s.opSetRepoCIPaused(r.Context(), apiUser(r), repo, *body.CIPaused)) {
			return
		}
	}
	repo, _ = s.Store.RepoByPath(r.Context(), repo.OwnerPath, repo.Name)
	writeJSON(w, http.StatusOK, s.projectJSONFull(r, repo))
}

func (s *Server) apiDeleteProject(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	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.opDeleteRepo(r.Context(), apiUser(r), repo, body.Confirm, forceParam(r))) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiStar(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	on, err := s.opToggleStar(r.Context(), apiUser(r), repo)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"starred": on})
}

func (s *Server) apiMembers(w http.ResponseWriter, r *http.Request, kind string, id int64) {
	if r.Method == http.MethodGet {
		list, err := s.Store.ListMembers(r.Context(), kind, id)
		if !s.apiOK(w, r, err) {
			return
		}
		page, per := pageQuery(r)
		rows := make([]map[string]any, 0, len(list))
		for _, m := range list {
			rows = append(rows, memberJSON(m))
		}
		writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
		return
	}
	var body struct {
		Username string `json:"username"`
		Role     string `json:"role"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opSetMember(r.Context(), apiUser(r), kind, id, body.Username, body.Role)) {
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"username": body.Username, "role": body.Role})
}

func (s *Server) apiGroupMembers(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	g, ok := s.apiGroup(w, r, min)
	if !ok {
		return
	}
	s.apiMembers(w, r, "group", g.ID)
}

func (s *Server) apiProjectMembers(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	repo, _, ok := s.apiRepo(w, r, min)
	if !ok {
		return
	}
	s.apiMembers(w, r, "repo", repo.ID)
}

func (s *Server) apiDeleteMember(w http.ResponseWriter, r *http.Request, kind string, id int64) {
	if !s.apiOK(w, r, s.opRemoveMember(r.Context(), apiUser(r), kind, id, r.PathValue("username"))) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiDeleteGroupMember(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiDeleteMember(w, r, "group", g.ID)
}

func (s *Server) apiDeleteProjectMember(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiDeleteMember(w, r, "repo", repo.ID)
}

func secretJSON(m store.SecretMeta) map[string]any {
	return map[string]any{"name": m.Name, "protected": m.Protected, "expand": m.Expand, "created_at": rfcTime(m.CreatedAt)}
}

func (s *Server) apiSecrets(w http.ResponseWriter, r *http.Request, kind string, id int64) {
	if r.Method == http.MethodGet {
		list, err := s.Store.ListSecrets(r.Context(), kind, id)
		if !s.apiOK(w, r, err) {
			return
		}
		rows := make([]map[string]any, 0, len(list))
		for _, m := range list {
			rows = append(rows, secretJSON(m))
		}
		page, per := pageQuery(r)
		writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
		return
	}
	var body struct {
		Name      string `json:"name"`
		Value     string `json:"value"`
		Protected bool   `json:"protected"`
		Expand    *bool  `json:"expand"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opPutSecret(r.Context(), apiUser(r), kind, id, body.Name, body.Value, body.Protected)) {
		return
	}
	if body.Expand != nil {
		_ = s.Store.SetSecretExpand(r.Context(), kind, id, body.Name, *body.Expand)
	}
	writeJSON(w, http.StatusOK, map[string]any{"name": body.Name})
}

func (s *Server) apiGroupSecrets(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	g, ok := s.apiGroup(w, r, min)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		if err := s.manageScope(r.Context(), apiUser(r), "group", g.ID); err != nil {
			s.writeAPIErr(w, r, err)
			return
		}
	}
	s.apiSecrets(w, r, "group", g.ID)
}

func (s *Server) apiProjectSecrets(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	repo, _, ok := s.apiRepo(w, r, min)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		if err := s.manageScope(r.Context(), apiUser(r), "repo", repo.ID); err != nil {
			s.writeAPIErr(w, r, err)
			return
		}
	}
	s.apiSecrets(w, r, "repo", repo.ID)
}

func (s *Server) apiDeleteSecret(w http.ResponseWriter, r *http.Request, kind string, id int64) {
	if !s.apiOK(w, r, s.opDeleteSecret(r.Context(), apiUser(r), kind, id, r.PathValue("name"))) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiDeleteGroupSecret(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiDeleteSecret(w, r, "group", g.ID)
}

func (s *Server) apiDeleteProjectSecret(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiDeleteSecret(w, r, "repo", repo.ID)
}

func hookJSON(h store.Webhook) map[string]any {
	return map[string]any{
		"id": h.ID, "name": h.Name, "preset": h.Preset, "url": h.URLTemplate,
		"method": h.Method, "events": h.Events, "branch_filter": h.BranchFilter, "active": h.Active,
	}
}

func (s *Server) apiHooks(w http.ResponseWriter, r *http.Request, kind string, id int64) {
	if r.Method == http.MethodGet {
		list, err := s.Store.ListWebhooks(r.Context(), kind, id)
		if !s.apiOK(w, r, err) {
			return
		}
		rows := make([]map[string]any, 0, len(list))
		for _, h := range list {
			rows = append(rows, hookJSON(h))
		}
		page, per := pageQuery(r)
		writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
		return
	}
	var body struct {
		Name         string   `json:"name"`
		Preset       string   `json:"preset"`
		BranchFilter string   `json:"branch_filter"`
		Events       []string `json:"events"`
		URL          string   `json:"url"`
		Username     string   `json:"username"`
		Avatar       string   `json:"avatar"`
		Icon         string   `json:"icon"`
		Alias        string   `json:"alias"`
		Token        string   `json:"token"`
		Chat         string   `json:"chat"`
		Server       string   `json:"server"`
		Topic        string   `json:"topic"`
		Homeserver   string   `json:"homeserver"`
		Room         string   `json:"room"`
		Method       string   `json:"method"`
		ContentType  string   `json:"content_type"`
		Headers      string   `json:"headers"`
		Body         string   `json:"body"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	wid, err := s.opCreateWebhook(r.Context(), apiUser(r), kind, id, hookIn{
		Name: body.Name, Preset: body.Preset, Filter: body.BranchFilter, Events: body.Events,
		Fields: webhook.Input{
			URL: body.URL, Username: body.Username, Avatar: body.Avatar, Icon: body.Icon, Alias: body.Alias,
			Token: body.Token, Chat: body.Chat, Server: body.Server, Topic: body.Topic,
			Homeserver: body.Homeserver, Room: body.Room, Method: body.Method, ContentType: body.ContentType,
			Headers: body.Headers, Body: body.Body,
		},
	})
	if !s.apiOK(w, r, err) {
		return
	}
	hook, err := s.Store.Webhook(r.Context(), kind, id, wid)
	if err != nil {
		writeJSON(w, http.StatusCreated, map[string]any{"id": wid})
		return
	}
	writeJSON(w, http.StatusCreated, hookJSON(hook))
}

func (s *Server) apiGroupHooks(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiHooks(w, r, "group", g.ID)
}

func (s *Server) apiProjectHooks(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiHooks(w, r, "repo", repo.ID)
}

func (s *Server) apiDeleteHook(w http.ResponseWriter, r *http.Request, kind string, id int64) {
	hid, 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.opDeleteWebhook(r.Context(), apiUser(r), kind, id, hid)) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

func (s *Server) apiDeleteGroupHook(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiDeleteHook(w, r, "group", g.ID)
}

func (s *Server) apiDeleteProjectHook(w http.ResponseWriter, r *http.Request) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	s.apiDeleteHook(w, r, "repo", repo.ID)
}

func approvalJSON(p store.ApprovalPolicy, locked string) map[string]any {
	return map[string]any{
		"configured": p.Configured, "maintainer_required": p.MaintainerRequired,
		"required_count": p.RequiredCount, "developers_approve": p.DevelopersApprove,
		"locked_by": locked,
	}
}

func approvalBody(r *http.Request) (store.ApprovalPolicy, error) {
	var body struct {
		MaintainerRequired bool `json:"maintainer_required"`
		RequiredCount      int  `json:"required_count"`
		DevelopersApprove  bool `json:"developers_approve"`
	}
	if err := readJSON(r, &body); err != nil {
		return store.ApprovalPolicy{}, fail(400, i18n.E("err.json"))
	}
	return store.ApprovalPolicy{
		MaintainerRequired: body.MaintainerRequired,
		RequiredCount:      body.RequiredCount,
		DevelopersApprove:  body.DevelopersApprove,
	}, nil
}

func (s *Server) apiGroupApproval(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	g, ok := s.apiGroup(w, r, min)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		p, err := s.Store.GetApproval(r.Context(), "group", g.ID)
		if !s.apiOK(w, r, err) {
			return
		}
		writeJSON(w, http.StatusOK, approvalJSON(p, ""))
		return
	}
	pol, err := approvalBody(r)
	if !s.apiOK(w, r, err) {
		return
	}
	if !s.apiOK(w, r, s.opSaveGroupApproval(r.Context(), apiUser(r), g, pol)) {
		return
	}
	writeJSON(w, http.StatusOK, approvalJSON(pol, ""))
}

func (s *Server) apiProjectApproval(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	repo, _, ok := s.apiRepo(w, r, min)
	if !ok {
		return
	}
	pol, locked, err := s.Store.EffectiveApproval(r.Context(), repo)
	if !s.apiOK(w, r, err) {
		return
	}
	if r.Method == http.MethodGet {
		writeJSON(w, http.StatusOK, approvalJSON(pol, locked))
		return
	}
	next, err := approvalBody(r)
	if !s.apiOK(w, r, err) {
		return
	}
	if !s.apiOK(w, r, s.opSaveRepoApproval(r.Context(), apiUser(r), repo, next)) {
		return
	}
	writeJSON(w, http.StatusOK, approvalJSON(next, ""))
}

func (s *Server) apiLogo(w http.ResponseWriter, r *http.Request, kind string, id int64, mime string) {
	if r.Method == http.MethodGet {
		s.serveLogo(w, r, kind, id, mime)
		return
	}
	if err := r.ParseMultipartForm(2 << 20); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.badForm")))
		return
	}
	if err := s.storeLogo(r, kind, id); err != nil {
		s.writeAPIErr(w, r, fail(400, err))
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"logo": true})
}

func (s *Server) apiGroupLogo(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	g, ok := s.apiGroup(w, r, min)
	if !ok {
		return
	}
	s.apiLogo(w, r, "group", g.ID, g.LogoMIME)
}

func (s *Server) apiProjectLogo(w http.ResponseWriter, r *http.Request) {
	min := access.RoleReadonly
	if r.Method != http.MethodGet {
		min = access.RoleMaintainer
	}
	repo, _, ok := s.apiRepo(w, r, min)
	if !ok {
		return
	}
	s.apiLogo(w, r, "repo", repo.ID, repo.LogoMIME)
}

func (s *Server) apiPatterns(w http.ResponseWriter, r *http.Request, tag bool) {
	repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	if r.Method == http.MethodGet {
		var list []string
		var err error
		if tag {
			list, err = s.Store.ProtectedTagPatterns(r.Context(), repo.ID)
		} else {
			list, err = s.Store.ProtectedPatterns(r.Context(), repo.ID)
		}
		if !s.apiOK(w, r, err) {
			return
		}
		if list == nil {
			list = []string{}
		}
		writeJSON(w, http.StatusOK, list)
		return
	}
	if _, _, ok := s.apiRepo(w, r, access.RoleMaintainer); !ok {
		return
	}
	var body struct {
		Pattern string `json:"pattern"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	if !s.apiOK(w, r, s.opProtect(r.Context(), apiUser(r), repo, body.Pattern, tag)) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{"pattern": body.Pattern})
}

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

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

func (s *Server) apiUnprotect(w http.ResponseWriter, r *http.Request, tag bool) {
	repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	pattern := pathWildcard(r, "pattern")
	if pattern == "" {
		pattern = decodeBranch(r.URL.Query().Get("pattern"))
	}
	if pattern == "" {
		var body struct {
			Pattern string `json:"pattern"`
		}
		if err := readJSON(r, &body); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		pattern = decodeBranch(body.Pattern)
	}
	if pattern == "" {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.notFound")))
		return
	}
	if !s.apiOK(w, r, s.opUnprotect(r.Context(), apiUser(r), repo, pattern, tag)) {
		return
	}
	writeJSON(w, http.StatusNoContent, nil)
}

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

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

// projectJSONFull is projectJSON plus stale_manual_days (-1 = instance-instelling).
func (s *Server) projectJSONFull(r *http.Request, repo store.Repo) map[string]any {
	out := projectJSON(repo)
	n, err := s.Store.RepoStaleManualDays(r.Context(), repo.ID)
	if err == nil {
		out["stale_manual_days"] = n
	}
	return out
}
