package server

import (
	"context"
	"encoding/json"
	"io"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"

	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/update"
)

const (
	updateLimit   = 5
	updateWindow  = time.Minute
	updateRunning = 30 * time.Minute
)

// UpdateView is de laatste self-update op de Info- en setup-pagina.
type UpdateView struct {
	When, SHA, Result, ResultLabel, Error string
	Has                                   bool
}

// UpdateStarter start de unit. Tests zetten een stub. Nil gebruikt systemctl.
type UpdateStarter func(ctx context.Context, ref string) error

type updateLimiter struct {
	mu sync.Mutex
	at map[string][]time.Time
}

func (l *updateLimiter) allow(ip string, now time.Time) bool {
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.at == nil {
		l.at = map[string][]time.Time{}
	}
	cut := now.Add(-updateWindow)
	keep := l.at[ip][:0]
	for _, ts := range l.at[ip] {
		if ts.After(cut) {
			keep = append(keep, ts)
		}
	}
	if len(keep) >= updateLimit {
		l.at[ip] = keep
		return false
	}
	l.at[ip] = append(keep, now)
	return true
}

func (s *Server) selfUpdate(w http.ResponseWriter, r *http.Request) {
	if !update.Enabled() {
		http.NotFound(w, r)
		return
	}
	if !s.updateHits.allow(clientIP(r), time.Now()) {
		http.Error(w, "too many requests\n", http.StatusTooManyRequests)
		return
	}
	if !update.Equal(update.Token(), bearer(r)) {
		http.Error(w, "unauthorized\n", http.StatusUnauthorized)
		return
	}
	raw, _ := io.ReadAll(io.LimitReader(r.Body, 4096))
	var flags struct {
		Force bool `json:"force"`
	}
	_ = json.Unmarshal(raw, &flags)
	r.Body = io.NopCloser(strings.NewReader(string(raw)))
	ref, err := updateRef(r)
	if err != nil {
		http.Error(w, "bad request\n", http.StatusBadRequest)
		return
	}
	if !update.ValidRef(ref) {
		http.Error(w, "bad request\n", http.StatusBadRequest)
		return
	}
	st, _ := update.ReadStatus(s.StateDir)
	if pending, _ := s.UpdateGate(); pending || update.FreshRunning(st, time.Now(), updateRunning) {
		if flags.Force {
			_ = s.setUpdateForce(true)
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			w.WriteHeader(http.StatusAccepted)
			_ = json.NewEncoder(w).Encode(map[string]string{"status": "forced", "ref": st.SHA})
			return
		}
		http.Error(w, "update already running\n", http.StatusConflict)
		return
	}
	force := flags.Force
	if err := update.WriteRequest(s.StateDir, ref); err != nil {
		http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
		return
	}
	_ = s.setUpdateForce(force)
	_ = update.WriteStatus(s.StateDir, update.Status{
		Time: time.Now().UTC().Format(time.RFC3339), SHA: ref, Result: update.ResultWaiting,
	})
	start := s.UpdateStarter
	if start == nil {
		start = func(ctx context.Context, _ string) error { return update.StartSystemd(ctx) }
	}
	if err := start(r.Context(), ref); err != nil {
		_ = update.WriteStatus(s.StateDir, update.Status{
			Time: time.Now().UTC().Format(time.RFC3339), SHA: ref, Result: "failed", Error: "start",
		})
		http.Error(w, "start failed\n", http.StatusBadGateway)
		return
	}
	if s.Log != nil {
		s.Log.Info("self-update gestart", "ref", ref)
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusAccepted)
	_ = json.NewEncoder(w).Encode(map[string]string{"status": "accepted", "ref": ref})
}

func (s *Server) selfUpdateStatus(w http.ResponseWriter, r *http.Request) {
	if !update.Enabled() {
		http.NotFound(w, r)
		return
	}
	if !update.Equal(update.Token(), bearer(r)) {
		http.Error(w, "unauthorized\n", http.StatusUnauthorized)
		return
	}
	running := 0
	if s.Store != nil {
		n, err := s.Store.CountRunningJobs(r.Context())
		if err != nil {
			http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
			return
		}
		running = n
	}
	st, err := update.ReadStatus(s.StateDir)
	if err != nil {
		http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
		return
	}
	logText, err := update.ReadLogTail(s.StateDir, update.LogTailLines)
	if err != nil {
		http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	var upd any
	if st.Result != "" {
		upd = st
	}
	body := map[string]any{
		"running":    running,
		"status":     st.Result,
		"sha":        st.SHA,
		"started_at": st.Time,
		"result":     st.Result,
		"log":        logText,
		"update":     upd,
		// force: de updater wacht niet langer op lopende jobs.
		"force":             s.updateForced(),
		"waiting_pipelines": s.countHeld(r.Context()),
		"max_wait_seconds":  int(s.updateMaxWait().Seconds()),
	}
	if st.Error != "" {
		body["error"] = st.Error
	}
	_ = json.NewEncoder(w).Encode(body)
}

func updateRef(r *http.Request) (string, error) {
	raw, err := io.ReadAll(io.LimitReader(r.Body, 4096))
	if err != nil {
		return "", err
	}
	if strings.TrimSpace(string(raw)) == "" {
		return "", nil
	}
	var body struct {
		Ref   string `json:"ref"`
		SHA   string `json:"sha"`
		Force bool   `json:"force"`
	}
	if err := json.Unmarshal(raw, &body); err != nil {
		return "", err
	}
	ref := strings.TrimSpace(body.Ref)
	sha := strings.TrimSpace(body.SHA)
	if ref != "" && sha != "" && ref != sha {
		return "", errMismatch
	}
	if ref == "" {
		ref = sha
	}
	return ref, nil
}

var errMismatch = errString("ref")

type errString string

func (e errString) Error() string { return string(e) }

func clientIP(r *http.Request) string {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return host
}

func (s *Server) attachUpdate(v *View, lang i18n.Lang) {
	if v.User == nil || !v.User.InstanceAdmin {
		return
	}
	v.ShowUpdate = true
	st, err := update.ReadStatus(s.StateDir)
	if err != nil || st.Result == "" {
		return
	}
	label := i18n.T(lang, "update.result."+st.Result)
	if label == "update.result."+st.Result {
		label = st.Result
	}
	v.Update = &UpdateView{
		When: st.Time, SHA: st.SHA, Result: st.Result, ResultLabel: label, Error: st.Error, Has: true,
	}
}
