package server

import (
	"net/http"
	"path/filepath"
	"strconv"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/auth"
	"gitlab.com/Timfa/bluegit/internal/config"
	"gitlab.com/Timfa/bluegit/internal/i18n"
)

// ApplySSH past een wijziging van de git-SSH-listener live toe.
// Nil: alleen opslaan; de listener verandert bij de volgende start.
type ApplySSHFunc func(enabled bool, listen string) error

// InstanceView is de machineconfiguratie voor de UI en API, zonder geheimen.
type InstanceView struct {
	BaseURL        string             `json:"base_url"`
	Listen         string             `json:"listen"`
	Listening      string             `json:"listening,omitempty"`
	ListenNotice   string             `json:"listen_notice,omitempty"`
	StatePath      string             `json:"state_path"`
	ConfigPath     string             `json:"config_path,omitempty"`
	SettingsPath   string             `json:"settings_path,omitempty"`
	StoragePath    string             `json:"storage_path,omitempty"`
	TrustedProxies []string           `json:"trusted_proxies"`
	Auth           InstanceAuthView   `json:"auth"`
	Git            InstanceGitView    `json:"git"`
	SSH            InstanceSSHView    `json:"ssh"`
	Runner         InstanceRunnerView `json:"runner"`
	CI             InstanceCIView     `json:"ci"`
}

// InstanceAuthView is auth zonder het clientgeheim zelf.
type InstanceAuthView struct {
	Mode             string `json:"mode"`
	BaseURL          string `json:"base_url"`
	ClientID         string `json:"client_id"`
	ClientSecretSet  bool   `json:"client_secret_set"`
	ClientSecretFile string `json:"client_secret_file,omitempty"`
	RedirectPath     string `json:"redirect_path"`
	UserAgent        string `json:"user_agent"`
	TenantID         string `json:"tenant_id,omitempty"`
	Issuer           string `json:"issuer,omitempty"`
	DevUser          string `json:"dev_user,omitempty"`
	DevAuthID        int64  `json:"dev_auth_id,omitempty"`
}

// InstanceGitView is het git-blok.
type InstanceGitView struct {
	Binary              string `json:"binary"`
	DefaultBranch       string `json:"default_branch"`
	HookBinary          string `json:"hook_binary,omitempty"`
	MaintenanceInterval string `json:"maintenance_interval,omitempty"`
}

// InstanceSSHView is het ssh-blok.
type InstanceSSHView struct {
	Enabled    bool   `json:"enabled"`
	Listen     string `json:"listen"`
	PublicHost string `json:"public_host,omitempty"`
	PublicPort int    `json:"public_port"`
}

// InstanceRunnerView is de naam van de ingebouwde runner.
type InstanceRunnerView struct {
	Name string `json:"name"`
}

// InstanceCIView is het ci-blok zonder presets (die staan onder Beheer → Runner).
type InstanceCIView struct {
	Enabled          bool   `json:"enabled"`
	Docker           string `json:"docker_binary"`
	Concurrency      int    `json:"concurrency"`
	Network          string `json:"network"`
	TimeoutSec       int    `json:"timeout_seconds"`
	UpdateMaxWaitMin int    `json:"update_max_wait_minutes"`
}

func (s *Server) instanceView() InstanceView {
	c := s.Cfg
	return InstanceView{
		BaseURL:        c.BaseURL,
		Listen:         c.Listen,
		Listening:      s.BoundAddr(),
		ListenNotice:   s.ListenNotice,
		StatePath:      c.StatePath,
		ConfigPath:     s.ConfigPath,
		SettingsPath:   s.SettingsPath,
		StoragePath:    s.StoragePath(),
		TrustedProxies: append([]string(nil), c.TrustedProxies...),
		Auth: InstanceAuthView{
			Mode:             c.Auth.Mode,
			BaseURL:          c.Auth.BaseURL,
			ClientID:         c.Auth.ClientID,
			ClientSecretSet:  strings.TrimSpace(c.Auth.ClientSecret) != "",
			ClientSecretFile: c.Auth.ClientSecretFile,
			RedirectPath:     c.Auth.RedirectPath,
			UserAgent:        c.Auth.UserAgent,
			TenantID:         c.Auth.TenantID,
			Issuer:           c.Auth.Issuer,
			DevUser:          c.Auth.DevUser,
			DevAuthID:        c.Auth.DevAuthID,
		},
		Git: InstanceGitView{
			Binary:              c.Git.Binary,
			DefaultBranch:       c.Git.DefaultBranch,
			HookBinary:          c.Git.HookBinary,
			MaintenanceInterval: c.Git.MaintenanceInterval,
		},
		SSH: InstanceSSHView{
			Enabled:    c.SSH.Enabled,
			Listen:     c.SSH.Listen,
			PublicHost: c.SSH.PublicHost,
			PublicPort: c.SSH.PublicPort,
		},
		Runner: InstanceRunnerView{Name: c.Runner.Name},
		CI: InstanceCIView{
			Enabled:          c.CI.Enabled,
			Docker:           c.CI.Docker,
			Concurrency:      c.CI.Concurrency,
			Network:          c.CI.Network,
			TimeoutSec:       c.CI.TimeoutSec,
			UpdateMaxWaitMin: c.CI.UpdateMaxWaitMin,
		},
	}
}

func (s *Server) adminSettings(w http.ResponseWriter, r *http.Request) {
	if ok, _ := s.adminOnly(w, r); !ok {
		return
	}
	v := s.view(w, r, "title.adminSettings")
	v.Page = "adminsettings"
	iv := s.instanceView()
	v.Instance = &iv
	s.render(w, "adminsettings", v)
}

func (s *Server) adminSettingsSave(w http.ResponseWriter, r *http.Request) {
	if ok, _ := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
		return
	}
	_ = r.ParseForm()
	patch := patchFromForm(r)
	bound, err := s.ApplyInstance(patch)
	if err != nil {
		s.redirect(w, r, "/admin/settings", "", s.trErr(r, err))
		return
	}
	msg := s.tr(r, "admin.settings.saved")
	if bound != "" {
		msg = s.tr(r, "admin.settings.listenNow", bound)
	}
	s.redirect(w, r, "/admin/settings", msg, "")
}

func (s *Server) apiAdminSettings(w http.ResponseWriter, r *http.Request) {
	if !apiUser(r).InstanceAdmin {
		s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
		return
	}
	switch r.Method {
	case http.MethodGet:
		writeJSON(w, http.StatusOK, s.instanceView())
	case http.MethodPut:
		var in instancePatchJSON
		if err := readJSON(r, &in); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		notice, err := s.ApplyInstance(in.toPatch())
		if !s.apiOK(w, r, err) {
			return
		}
		out := s.instanceView()
		out.ListenNotice = notice
		writeJSON(w, http.StatusOK, out)
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

// ApplyInstance valideert, bindt listen/SSH indien nodig, slaat settings.yml
// op en zet de nieuwe waarden live. config.yml blijft ongemoeid.
func (s *Server) ApplyInstance(patch config.Persisted) (string, error) {
	next, saved := config.MergeUpdate(s.Cfg, patch)
	if err := next.Validate(); err != nil {
		return "", fail(400, err)
	}
	notice := ""
	if next.Listen != s.Cfg.Listen && s.isServing() {
		if err := s.Relisten(next.Listen); err != nil {
			return "", fail(400, err)
		}
		notice = s.BoundAddr()
		s.ListenNotice = notice
	}
	if s.ApplySSH != nil && (next.SSH.Enabled != s.Cfg.SSH.Enabled || next.SSH.Listen != s.Cfg.SSH.Listen) {
		if err := s.ApplySSH(next.SSH.Enabled, next.SSH.Listen); err != nil {
			return notice, fail(400, err)
		}
	}
	if dir := s.StateDir; dir != "" {
		if err := config.SaveSettings(dir, saved); err != nil {
			return notice, err
		}
		s.SettingsPath = filepath.Join(dir, config.SettingsFile)
	}
	s.Cfg = next
	if next.Git.Binary != "" {
		s.Git = next.Git.Binary
	}
	if next.Git.HookBinary != "" {
		s.HookBin = next.Git.HookBinary
	}
	s.applyAuth(next)
	if s.Runner != nil {
		s.Runner.BaseURL = next.BaseURL
		if next.Runner.Name != "" {
			s.Runner.Name = next.Runner.Name
		}
		if next.CI.Docker != "" {
			s.Runner.Docker = next.CI.Docker
		}
	}
	return notice, nil
}

func (s *Server) applyAuth(cfg config.Config) {
	switch cfg.Auth.Mode {
	case "dev":
		s.Auth = auth.Dev{Username: cfg.Auth.DevUser, AuthID: cfg.Auth.DevAuthID}
		s.Dev = true
	case "entra":
		s.Auth = auth.NewEntra(cfg.EntraIssuer(), cfg.Auth.TenantID, cfg.Auth.ClientID, cfg.Auth.ClientSecret, cfg.Auth.UserAgent)
		s.Dev = false
	default:
		s.Auth = auth.NewTimFalken(cfg.Auth.BaseURL, cfg.Auth.ClientID, cfg.Auth.ClientSecret, cfg.Auth.UserAgent)
		s.Dev = false
	}
	if m, ok := s.Auth.(auth.Mailer); ok && cfg.Auth.ClientSecret != "" {
		s.Mail = m
	} else {
		s.Mail = nil
	}
}

func formLast(r *http.Request, name string) (string, bool) {
	vals, ok := r.Form[name]
	if !ok || len(vals) == 0 {
		return "", false
	}
	return strings.TrimSpace(vals[len(vals)-1]), true
}

func patchFromForm(r *http.Request) config.Persisted {
	str := func(name string) *string {
		v, ok := formLast(r, name)
		if !ok {
			return nil
		}
		return &v
	}
	boolp := func(name string) *bool {
		v, ok := formLast(r, name)
		if !ok {
			return nil
		}
		b := v == "1" || v == "on" || v == "true"
		return &b
	}
	intp := func(name string) *int {
		v, ok := formLast(r, name)
		if !ok {
			return nil
		}
		n, err := strconv.Atoi(v)
		if err != nil {
			return nil
		}
		return &n
	}
	int64p := func(name string) *int64 {
		v, ok := formLast(r, name)
		if !ok {
			return nil
		}
		n, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			return nil
		}
		return &n
	}
	var proxies *[]string
	if _, ok := r.Form["trusted_proxies"]; ok {
		var list []string
		for _, line := range strings.Split(r.FormValue("trusted_proxies"), "\n") {
			line = strings.TrimSpace(line)
			if line != "" {
				list = append(list, line)
			}
		}
		if list == nil {
			list = []string{}
		}
		proxies = &list
	}
	p := config.Persisted{
		BaseURL:        str("base_url"),
		Listen:         str("listen"),
		TrustedProxies: proxies,
		Auth: &config.PersistedAuth{
			Mode:             str("auth.mode"),
			BaseURL:          str("auth.base_url"),
			ClientID:         str("auth.client_id"),
			ClientSecret:     str("auth.client_secret"),
			ClientSecretFile: str("auth.client_secret_file"),
			RedirectPath:     str("auth.redirect_path"),
			UserAgent:        str("auth.user_agent"),
			DevUser:          str("auth.dev_user"),
			DevAuthID:        int64p("auth.dev_auth_id"),
			TenantID:         str("auth.tenant_id"),
			Issuer:           str("auth.issuer"),
		},
		Git: &config.PersistedGit{
			Binary:              str("git.binary"),
			DefaultBranch:       str("git.default_branch"),
			HookBinary:          str("git.hook_binary"),
			MaintenanceInterval: str("git.maintenance_interval"),
		},
		SSH: &config.PersistedSSH{
			Enabled:    boolp("ssh.enabled"),
			Listen:     str("ssh.listen"),
			PublicHost: str("ssh.public_host"),
			PublicPort: intp("ssh.public_port"),
		},
		Runner: &config.PersistedRunner{Name: str("runner.name")},
		CI: &config.PersistedCI{
			Enabled:          boolp("ci.enabled"),
			Docker:           str("ci.docker_binary"),
			Concurrency:      intp("ci.concurrency"),
			Network:          str("ci.network"),
			TimeoutSec:       intp("ci.timeout_seconds"),
			UpdateMaxWaitMin: intp("ci.update_max_wait_minutes"),
		},
	}
	return p
}

type instancePatchJSON struct {
	BaseURL        *string   `json:"base_url"`
	Listen         *string   `json:"listen"`
	TrustedProxies *[]string `json:"trusted_proxies"`
	Auth           *struct {
		Mode             *string `json:"mode"`
		BaseURL          *string `json:"base_url"`
		ClientID         *string `json:"client_id"`
		ClientSecret     *string `json:"client_secret"`
		ClientSecretFile *string `json:"client_secret_file"`
		RedirectPath     *string `json:"redirect_path"`
		UserAgent        *string `json:"user_agent"`
		DevUser          *string `json:"dev_user"`
		DevAuthID        *int64  `json:"dev_auth_id"`
		TenantID         *string `json:"tenant_id"`
		Issuer           *string `json:"issuer"`
	} `json:"auth"`
	Git *struct {
		Binary              *string `json:"binary"`
		DefaultBranch       *string `json:"default_branch"`
		HookBinary          *string `json:"hook_binary"`
		MaintenanceInterval *string `json:"maintenance_interval"`
	} `json:"git"`
	SSH *struct {
		Enabled    *bool   `json:"enabled"`
		Listen     *string `json:"listen"`
		PublicHost *string `json:"public_host"`
		PublicPort *int    `json:"public_port"`
	} `json:"ssh"`
	Runner *struct {
		Name *string `json:"name"`
	} `json:"runner"`
	CI *struct {
		Enabled          *bool   `json:"enabled"`
		Docker           *string `json:"docker_binary"`
		Concurrency      *int    `json:"concurrency"`
		Network          *string `json:"network"`
		TimeoutSec       *int    `json:"timeout_seconds"`
		UpdateMaxWaitMin *int    `json:"update_max_wait_minutes"`
	} `json:"ci"`
}

func (in instancePatchJSON) toPatch() config.Persisted {
	p := config.Persisted{BaseURL: in.BaseURL, Listen: in.Listen, TrustedProxies: in.TrustedProxies}
	if a := in.Auth; a != nil {
		p.Auth = &config.PersistedAuth{
			Mode: a.Mode, BaseURL: a.BaseURL, ClientID: a.ClientID, ClientSecret: a.ClientSecret,
			ClientSecretFile: a.ClientSecretFile, RedirectPath: a.RedirectPath, UserAgent: a.UserAgent,
			DevUser: a.DevUser, DevAuthID: a.DevAuthID, TenantID: a.TenantID, Issuer: a.Issuer,
		}
	}
	if g := in.Git; g != nil {
		p.Git = &config.PersistedGit{Binary: g.Binary, DefaultBranch: g.DefaultBranch, HookBinary: g.HookBinary, MaintenanceInterval: g.MaintenanceInterval}
	}
	if h := in.SSH; h != nil {
		p.SSH = &config.PersistedSSH{Enabled: h.Enabled, Listen: h.Listen, PublicHost: h.PublicHost, PublicPort: h.PublicPort}
	}
	if r := in.Runner; r != nil {
		p.Runner = &config.PersistedRunner{Name: r.Name}
	}
	if c := in.CI; c != nil {
		p.CI = &config.PersistedCI{Enabled: c.Enabled, Docker: c.Docker, Concurrency: c.Concurrency, Network: c.Network, TimeoutSec: c.TimeoutSec, UpdateMaxWaitMin: c.UpdateMaxWaitMin}
	}
	return p
}
