package server

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

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

// Runnerbeheer via de API: dezelfde regels als de UI. Account-runners
// alleen voor de eigenaar zelf, groepsrunners alleen voor maintainers.
// Scope runners (of api; read_api voor lezen). Job-tokens (bgj_) en
// runner-tokens (bgr_) komen hier niet in: authUser accepteert alleen bg_.

func runnerJSON(r store.Runner) map[string]any {
	status := "offline"
	if r.Paused {
		status = "paused"
	} else if r.Draining && r.Online(time.Now()) {
		status = "draining"
	} else if r.Online(time.Now()) {
		status = "online"
	}
	return map[string]any{
		"id": r.ID, "name": r.Name, "owner_kind": r.OwnerKind, "owner_id": r.OwnerID,
		"status": status, "online": r.Online(time.Now()), "paused": r.Paused, "draining": r.Draining,
		"last_seen": rfcTime(r.LastSeen), "created_at": rfcTime(r.CreatedAt), "version": r.Version,
	}
}

// runnerScope bepaalt de eigenaar uit het pad: /user/... of /groups/{path}/...
func (s *Server) runnerScope(w http.ResponseWriter, r *http.Request) (string, int64, bool) {
	if strings.HasPrefix(r.URL.Path, "/api/v1/admin/runners") {
		if !apiUser(r).InstanceAdmin {
			s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.onlyAdmin")))
			return "", 0, false
		}
		return store.RunnerGlobal, 0, true
	}
	if r.PathValue("path") != "" {
		g, ok := s.apiGroup(w, r, access.RoleMaintainer)
		if !ok {
			return "", 0, false
		}
		return "group", g.ID, true
	}
	return "user", apiUser(r).ID, true
}

func (s *Server) scopedRunner(w http.ResponseWriter, r *http.Request) (string, int64, store.Runner, bool) {
	kind, owner, ok := s.runnerScope(w, r)
	if !ok {
		return "", 0, store.Runner{}, false
	}
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	rn, rerr := s.Store.RunnerByID(r.Context(), id)
	if err != nil || rerr != nil || rn.Revoked || rn.OwnerKind != kind || rn.OwnerID != owner {
		s.writeAPIErr(w, r, fail(http.StatusNotFound, i18n.E("err.notFound")))
		return "", 0, store.Runner{}, false
	}
	return kind, owner, rn, true
}

func (s *Server) apiRunners(w http.ResponseWriter, r *http.Request) {
	kind, owner, ok := s.runnerScope(w, r)
	if !ok {
		return
	}
	rs, err := s.Store.ListRunners(r.Context(), kind, owner)
	if !s.apiOK(w, r, err) {
		return
	}
	out := make([]map[string]any, 0, len(rs))
	for _, rn := range rs {
		out = append(out, runnerJSON(rn))
	}
	writeJSON(w, http.StatusOK, out)
}

func (s *Server) apiRunnerRegToken(w http.ResponseWriter, r *http.Request) {
	kind, owner, ok := s.runnerScope(w, r)
	if !ok {
		return
	}
	plain, err := s.Store.CreateRunnerRegToken(r.Context(), kind, owner, apiUser(r).ID)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusCreated, map[string]any{
		"token": plain, "owner_kind": kind, "owner_id": owner,
		"expires_at": rfcTime(time.Now().Add(24 * time.Hour)),
		"warning":    globalWarning(kind),
		"register":   "bluegit-runner register --url " + s.Cfg.BaseURL + " --token <token>",
	})
}

func (s *Server) apiRunnerGet(w http.ResponseWriter, r *http.Request) {
	if _, _, rn, ok := s.scopedRunner(w, r); ok {
		writeJSON(w, http.StatusOK, runnerJSON(rn))
	}
}

func (s *Server) apiRunnerPut(w http.ResponseWriter, r *http.Request) {
	kind, owner, rn, ok := s.scopedRunner(w, r)
	if !ok {
		return
	}
	var body struct {
		Name   *string `json:"name"`
		Paused *bool   `json:"paused"`
	}
	if err := readJSON(r, &body); err != nil {
		s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
		return
	}
	upd, err := s.Store.UpdateRunner(r.Context(), kind, owner, rn.ID, body.Name, body.Paused)
	if err != nil {
		s.writeAPIErr(w, r, fail(400, err))
		return
	}
	writeJSON(w, http.StatusOK, runnerJSON(upd))
}

func (s *Server) setPaused(w http.ResponseWriter, r *http.Request, paused bool) {
	kind, owner, rn, ok := s.scopedRunner(w, r)
	if !ok {
		return
	}
	upd, err := s.Store.UpdateRunner(r.Context(), kind, owner, rn.ID, nil, &paused)
	if !s.apiOK(w, r, err) {
		return
	}
	writeJSON(w, http.StatusOK, runnerJSON(upd))
}

func (s *Server) apiRunnerPause(w http.ResponseWriter, r *http.Request)  { s.setPaused(w, r, true) }
func (s *Server) apiRunnerResume(w http.ResponseWriter, r *http.Request) { s.setPaused(w, r, false) }

func (s *Server) apiRunnerDelete(w http.ResponseWriter, r *http.Request) {
	kind, owner, rn, ok := s.scopedRunner(w, r)
	if !ok {
		return
	}
	if !s.apiOK(w, r, s.revokeRunner(r.Context(), kind, owner, rn.ID, forceParam(r))) {
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) apiRunnerJobs(w http.ResponseWriter, r *http.Request) {
	_, _, rn, ok := s.scopedRunner(w, r)
	if !ok {
		return
	}
	limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
	jobs, err := s.Store.RunnerJobs(r.Context(), rn.ID, limit)
	if !s.apiOK(w, r, err) {
		return
	}
	uid := apiUser(r).ID
	out := []map[string]any{}
	for _, j := range jobs {
		row := map[string]any{"id": j.JobID, "pipeline_id": j.PipelineID, "name": j.Name, "status": j.Status,
			"started_at": rfcTime(j.StartedAt), "finished_at": rfcTime(j.FinishedAt), "project": nil}
		// Alleen projectnamen die de vrager zelf mag zien.
		if repo, err := s.Store.RepoByID(r.Context(), j.RepoID); err == nil {
			if role, err := s.Store.EffectiveRole(r.Context(), uid, repo.ID); err == nil && (role.CanRead() || repo.Visibility == "public") {
				row["project"] = repo.FullPath()
				row["web_url"] = s.Cfg.BaseURL + "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(j.PipelineID, 10) + "/jobs/" + strconv.FormatInt(j.JobID, 10)
			}
		}
		out = append(out, row)
	}
	writeJSON(w, http.StatusOK, out)
}

func (s *Server) apiUserRunnerSettings(w http.ResponseWriter, r *http.Request) {
	u := apiUser(r)
	if r.Method == http.MethodPut {
		var body struct {
			Preference string `json:"preference"`
		}
		if err := readJSON(r, &body); err != nil || (body.Preference != store.RunnerPrefOwnFirst && body.Preference != store.RunnerPrefBuiltinFirst) {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		if !s.apiOK(w, r, s.Store.SetUserRunnerPref(r.Context(), u.ID, body.Preference)) {
			return
		}
	}
	writeJSON(w, http.StatusOK, map[string]any{"preference": s.Store.UserRunnerPref(r.Context(), u.ID)})
}

func (s *Server) apiGroupRunnerSettings(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleMaintainer)
	if !ok {
		return
	}
	if r.Method == http.MethodPut {
		var body struct {
			BuiltinFirst *bool `json:"builtin_first"`
		}
		if err := readJSON(r, &body); err != nil || body.BuiltinFirst == nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		if !s.apiOK(w, r, s.Store.SetGroupBuiltinFirst(r.Context(), g.ID, *body.BuiltinFirst)) {
			return
		}
	}
	ids, _ := s.Store.RunnerOptIns(r.Context(), g.ID)
	names := []string{}
	for _, id := range ids {
		if u, err := s.Store.UserByID(r.Context(), id); err == nil {
			names = append(names, u.Username)
		}
	}
	writeJSON(w, http.StatusOK, map[string]any{"builtin_first": s.Store.GroupBuiltinFirst(r.Context(), g.ID), "opted_in": names})
}

// apiGroupRunnerOptIn: alleen je eigen toestemming, en alleen als maintainer.
func (s *Server) apiGroupRunnerOptIn(w http.ResponseWriter, r *http.Request) {
	g, ok := s.apiGroup(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	u := apiUser(r)
	if r.Method == http.MethodPut {
		var body struct {
			Enabled *bool `json:"enabled"`
		}
		if err := readJSON(r, &body); err != nil || body.Enabled == nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		if !s.apiOK(w, r, s.Store.SetRunnerOptIn(r.Context(), g.ID, u.ID, *body.Enabled)) {
			return
		}
	}
	ids, _ := s.Store.RunnerOptIns(r.Context(), g.ID)
	on := false
	for _, id := range ids {
		on = on || id == u.ID
	}
	writeJSON(w, http.StatusOK, map[string]any{"enabled": on, "username": u.Username})
}

// globalWarning: een globale runner krijgt jobs uit alle repo's, ook privé.
func globalWarning(kind string) string {
	if kind != store.RunnerGlobal {
		return ""
	}
	return "A global runner receives jobs (code and that job's secrets) from every repository, public and private. Only register machines you fully trust."
}
