// Package server is de webinterface, de git-HTTP-server en de API.
package server

import (
	"context"
	"crypto/rand"
	"embed"
	"encoding/hex"
	"html/template"
	"io/fs"
	"log/slog"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"
	"unicode/utf8"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/activity"
	"gitlab.com/Timfa/bluegit/internal/auth"
	"gitlab.com/Timfa/bluegit/internal/config"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/realip"
	"gitlab.com/Timfa/bluegit/internal/runner"
	"gitlab.com/Timfa/bluegit/internal/store"
)

//go:embed templates/*.html static/*
var webFS embed.FS

// Server bedient BlueGit.
type Server struct {
	Cfg     config.Config
	Store   *store.Store
	Auth    auth.Provider
	Mail    auth.Mailer
	Dev     bool
	Git     string
	HookBin string
	Runner  *runner.Runner
	Log     *slog.Logger
	// StateDir is de map met database en het bestand storage_path.
	StateDir string
	// AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
	AfterStorage func(path string)
	tmpl         *template.Template
	byLang       map[string]*template.Template

	storageMu  sync.RWMutex
	storage    string
	storageSet bool
}

type principal struct {
	User    store.User
	Session store.Session
	OK      bool
}

type ctxKey struct{}

// Handler is de HTTP-handler met sessies en koppen.
func (s *Server) Handler() http.Handler {
	s.mustTemplates()
	mux := http.NewServeMux()
	mux.HandleFunc("GET /assets/{file}", s.asset)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok\n"))
	})
	mux.HandleFunc("GET /login", s.login)
	mux.HandleFunc("GET /auth/callback", s.callback)
	mux.HandleFunc("POST /logout", s.logout)
	mux.HandleFunc("GET /{$}", s.home)
	mux.HandleFunc("GET /new", s.newPage)
	mux.HandleFunc("GET /new/slug", s.slugPreview)
	mux.HandleFunc("POST /new/repo", s.createRepo)
	mux.HandleFunc("POST /new/group", s.createGroup)
	mux.HandleFunc("GET /setup", s.setupPage)
	mux.HandleFunc("POST /setup", s.setupSave)
	mux.HandleFunc("GET /settings", s.account)
	mux.HandleFunc("POST /settings/language", s.saveLanguage)
	mux.HandleFunc("POST /settings/tokens", s.createToken)
	mux.HandleFunc("POST /settings/tokens/delete", s.deleteToken)
	mux.HandleFunc("POST /settings/ssh", s.addSSH)
	mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
	mux.HandleFunc("GET /settings/export", s.export)
	mux.HandleFunc("GET /users/{username}", s.profile)
	mux.HandleFunc("GET /groups/{path}", s.groupPage)
	mux.HandleFunc("GET /groups/{path}/logo", s.groupLogo)
	mux.HandleFunc("POST /groups/{path}/settings", s.saveGroup)
	mux.HandleFunc("POST /groups/{path}/approvals", s.saveGroupApproval)
	mux.HandleFunc("POST /groups/{path}/owner", s.transferGroup)
	mux.HandleFunc("POST /groups/{path}/logo", s.uploadGroupLogo)
	mux.HandleFunc("POST /groups/{path}/members", s.groupMember)
	mux.HandleFunc("POST /groups/{path}/members/remove", s.groupMemberRemove)
	mux.HandleFunc("POST /groups/{path}/secrets", s.groupSecret)
	mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
	mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
	mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)

	mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
	mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
	mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
	mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)

	mux.HandleFunc("GET /{owner}/{repo}", s.repoHome)
	mux.HandleFunc("GET /{owner}/{repo}/-/tree", s.treeRoot)
	mux.HandleFunc("GET /{owner}/{repo}/-/tree/{path...}", s.tree)
	mux.HandleFunc("GET /{owner}/{repo}/-/blob/{path...}", s.blob)
	mux.HandleFunc("GET /{owner}/{repo}/-/commits", s.commits)
	mux.HandleFunc("GET /{owner}/{repo}/-/tags", s.tags)
	mux.HandleFunc("GET /{owner}/{repo}/-/commit/{sha}", s.commit)
	mux.HandleFunc("GET /{owner}/{repo}/-/branches", s.branches)
	mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests", s.mergeRequests)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests", s.createMR)
	mux.HandleFunc("GET /{owner}/{repo}/-/merge-requests/{number}", s.showMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/merge", s.mergeMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/close", s.closeMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reopen", s.reopenMR)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews", s.postReview)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/reviews/dismiss", s.dismissReview)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/notes", s.createNote)
	mux.HandleFunc("POST /{owner}/{repo}/-/merge-requests/{number}/suggestions", s.applySuggestions)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines", s.pipelines)
	mux.HandleFunc("POST /{owner}/{repo}/-/pipelines", s.runPipeline)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}", s.pipeline)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}", s.showJob)
	mux.HandleFunc("GET /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/log", s.jobLog)
	mux.HandleFunc("POST /{owner}/{repo}/-/pipelines/{id}/jobs/{job}/play", s.playJob)
	mux.HandleFunc("GET /{owner}/{repo}/-/ci/editor", s.ciEditor)
	mux.HandleFunc("POST /{owner}/{repo}/-/ci/editor", s.saveCIEditor)
	mux.HandleFunc("POST /{owner}/{repo}/-/ci/lint", s.lintCI)
	mux.HandleFunc("GET /{owner}/{repo}/-/releases", s.releases)
	mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
	mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
	mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
	mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
	mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
	mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
	mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
	mux.HandleFunc("POST /{owner}/{repo}/-/members", s.repoMember)
	mux.HandleFunc("POST /{owner}/{repo}/-/members/remove", s.repoMemberRemove)
	mux.HandleFunc("POST /{owner}/{repo}/-/protected", s.addProtected)
	mux.HandleFunc("POST /{owner}/{repo}/-/protected/remove", s.removeProtected)
	mux.HandleFunc("POST /{owner}/{repo}/-/secrets", s.repoSecret)
	mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
	mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
	mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
	mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)

	return s.realIP(s.withSession(s.secure(s.gate(mux))))
}

func (s *Server) realIP(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		realip.Apply(r, s.Cfg.ProxySet())
		next.ServeHTTP(w, r)
	})
}

func (s *Server) mustTemplates() {
	if s.byLang != nil {
		return
	}
	s.byLang = map[string]*template.Template{}
	for _, lang := range i18n.All() {
		l := lang
		s.byLang[string(l)] = template.Must(template.New("web").Funcs(template.FuncMap{
			"short": func(v string) string {
				if len(v) > 10 {
					return v[:10]
				}
				return v
			},
			"join": strings.Join,
			"initial": func(s string) string {
				s = strings.TrimSpace(s)
				if s == "" {
					return "?"
				}
				r, _ := utf8.DecodeRuneInString(s)
				return strings.ToUpper(string(r))
			},
			"splitPath": func(p string) []string {
				if p == "" {
					return nil
				}
				return strings.Split(p, "/")
			},
			"iconOf": func(name string) string { return fileIcon(name, "blob") },
			"t":      func(key string, args ...any) string { return i18n.T(l, key, args...) },
			"tn": func(n int, one, many string) string {
				key := many
				if n == 1 {
					key = one
				}
				return i18n.T(l, key, n)
			},
			"roleName": func(r access.Role) string { return i18n.T(l, "role."+string(r)) },
			"visName":  func(v string) string { return i18n.T(l, "vis."+v) },
			"presetName": func(id string) string {
				label := i18n.T(l, "set.preset."+id)
				if label == "set.preset."+id {
					return id
				}
				return label
			},
		}).ParseFS(webFS, "templates/*.html"))
	}
	s.tmpl = s.byLang[string(i18n.EN)]
}

func (s *Server) asset(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("file")
	if name == "" || strings.Contains(name, "/") || strings.Contains(name, "..") {
		http.NotFound(w, r)
		return
	}
	sub, err := fs.Sub(webFS, "static")
	if err != nil {
		http.Error(w, "assets", http.StatusInternalServerError)
		return
	}
	http.ServeFileFS(w, r, sub, name)
}

func (s *Server) secure(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
		w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https://auth.timfalken.com data:; style-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'")
		next.ServeHTTP(w, r)
	})
}

func (s *Server) withSession(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		p := principal{}
		if c, err := r.Cookie("bluegit_session"); err == nil && c.Value != "" {
			sess, err := s.Store.Session(r.Context(), c.Value)
			if err == nil && sess.ExpiresAt.After(time.Now()) {
				p.Session = sess
				p.User = sess.User
				p.OK = true
				s.maybeExtend(r.Context(), sess)
			}
		}
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, p)))
	})
}

func (s *Server) maybeExtend(ctx context.Context, sess store.Session) {
	if time.Until(sess.ExpiresAt) > 6*time.Hour {
		return
	}
	sec, err := s.Auth.Extend(ctx, sess.AccessToken)
	if err != nil || sec <= 0 {
		return
	}
	_ = s.Store.UpdateSessionExpiry(ctx, sess.ID, time.Now().Add(time.Duration(sec)*time.Second))
}

func (s *Server) who(r *http.Request) principal {
	p, _ := r.Context().Value(ctxKey{}).(principal)
	return p
}

func (s *Server) csrfOK(w http.ResponseWriter, r *http.Request) bool {
	if err := r.ParseForm(); err != nil {
		http.Error(w, s.tr(r, "err.badForm"), http.StatusBadRequest)
		return false
	}
	p := s.who(r)
	if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
		http.Error(w, s.tr(r, "err.badCSRF"), http.StatusBadRequest)
		return false
	}
	return true
}

func (s *Server) loginRequired(w http.ResponseWriter, r *http.Request) (store.User, bool) {
	p := s.who(r)
	if !p.OK {
		http.Redirect(w, r, "/login", http.StatusFound)
		return store.User{}, false
	}
	return p.User, true
}

func (s *Server) setSessionCookie(w http.ResponseWriter, id string, exp time.Time) {
	http.SetCookie(w, &http.Cookie{
		Name:     "bluegit_session",
		Value:    id,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
		Secure:   strings.HasPrefix(s.Cfg.BaseURL, "https://"),
		Expires:  exp,
	})
}

func (s *Server) flash(w http.ResponseWriter, notice, problem string) {
	secure := strings.HasPrefix(s.Cfg.BaseURL, "https://")
	if notice != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: url.QueryEscape(notice), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
	}
	if problem != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: url.QueryEscape(problem), Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
	}
}

func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (string, string) {
	notice, problem := flashVal(r, "bluegit_notice"), flashVal(r, "bluegit_error")
	if notice != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_notice", Value: "", Path: "/", MaxAge: -1})
	}
	if problem != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: "", Path: "/", MaxAge: -1})
	}
	return notice, problem
}

func cookieVal(r *http.Request, name string) string {
	c, err := r.Cookie(name)
	if err != nil {
		return ""
	}
	return c.Value
}

func flashVal(r *http.Request, name string) string {
	raw := cookieVal(r, name)
	if raw == "" {
		return ""
	}
	v, err := url.QueryUnescape(raw)
	if err != nil {
		return raw
	}
	return v
}

func (s *Server) redirect(w http.ResponseWriter, r *http.Request, path, notice, problem string) {
	s.flash(w, notice, problem)
	http.Redirect(w, r, path, http.StatusSeeOther)
}

func (s *Server) langOf(r *http.Request) i18n.Lang {
	if p := s.who(r); p.OK {
		return i18n.Parse(p.User.Language)
	}
	return i18n.EN
}

func (s *Server) tr(r *http.Request, key string, args ...any) string {
	return i18n.T(s.langOf(r), key, args...)
}

func (s *Server) trErr(r *http.Request, err error) string {
	return i18n.Text(s.langOf(r), err)
}

func (s *Server) view(w http.ResponseWriter, r *http.Request, title string) View {
	notice, problem := s.takeFlash(w, r)
	lang := s.langOf(r)
	if strings.HasPrefix(title, "title.") {
		title = i18n.T(lang, title)
	}
	v := View{
		Title: title, BaseURL: s.Cfg.BaseURL, Notice: notice, Err: problem,
		StorageUnset: s.StoragePath() == "", Lang: string(lang), HTMLLang: htmlLang(lang),
		Cunei: lang == i18n.Cuneiform,
	}
	for _, l := range i18n.All() {
		v.Langs = append(v.Langs, LangChoice{Code: string(l), Label: l.Name()})
	}
	if p := s.who(r); p.OK {
		u := p.User
		v.User = &u
		v.CSRF = p.Session.CSRF
	}
	return v
}

func htmlLang(l i18n.Lang) string {
	switch l {
	case i18n.NL:
		return "nl"
	case i18n.DE:
		return "de"
	case i18n.FR:
		return "fr"
	default:
		return "en"
	}
}

func (s *Server) render(w http.ResponseWriter, name string, v View) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	tmpl := s.byLang[v.Lang]
	if tmpl == nil {
		tmpl = s.tmpl
	}
	if err := tmpl.ExecuteTemplate(w, name, v); err != nil && s.Log != nil {
		s.Log.Error("sjabloon", "name", name, "err", err)
	}
}

func randomState() (string, error) {
	b := make([]byte, 32)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}

// View is de gegevensset voor elk scherm.
type View struct {
	Title        string
	BaseURL      string
	User         *store.User
	CSRF         string
	Notice       string
	Err          string
	Repos        []store.Repo
	Groups       []store.Group
	Repo         *store.Repo
	Role         access.Role
	CanWrite     bool
	CanAdmin     bool
	CanMerge     bool
	CanComment   bool
	CanApply     bool
	Commits      []CommitRow
	Commit       *CommitRow
	Entries      []EntryRow
	TreePath     string
	Blob         string
	BlobPath     string
	Binary       bool
	Branches     []BranchRow
	MRs          []store.MergeRequest
	MR           *store.MergeRequest
	MRPipe       *PipeRow
	MergeBlocks  []string
	Approval     *ApprovalView
	Reviews      []ReviewRow
	CanReview    bool
	CanApprove   bool
	CanDismiss   bool
	CanClose     bool
	CanReopen    bool
	IsOwner      bool
	Candidates   []store.Member
	Diff         string
	DiffFiles    []DiffFileView
	Pipes        []store.Pipeline
	PipeRows     []PipeRow
	Pipe         *store.Pipeline
	Jobs         []store.Job
	JobPage      *JobPage
	Editor       *CIEditor
	Releases     []store.Release
	Members      []store.Member
	Secrets      []store.SecretMeta
	Hooks        []HookView
	Patterns     []string
	Tokens       []store.TokenInfo
	Keys         []store.SSHKey
	CloneHTTP    string
	CloneSSH     string
	Group        *store.Group
	Tab          string
	Rev          string
	NewToken     string
	StorageUnset bool
	StoragePath  string
	StorageFree  string
	StorageTotal string
	MinFree      string
	Wide         bool
	Page         string
	Lang         string
	HTMLLang     string
	Cunei        bool
	Langs        []LangChoice
	Query        string
	SortDir      string
	FlipDir      string
	Cards        []RepoCard
	Head         *CommitRow
	Files        []FileRow
	Tree         []FileRow
	Readme       template.HTML
	ReadmeName   string
	LicensePath  string
	NCommits     int
	NBranches    int
	NTags        int
	NReleases    int
	Created      string
	Lines        []CodeLine
	BlobSize     string
	FileName     string
	RevProtected bool
	TagNames     []string
	Heat         *activity.Calendar
	Notes        []NoteRow
	Profile      *store.User
}

// LangChoice is één taal in de instellingen.
type LangChoice struct {
	Code, Label string
}

// RepoCard is een repository in een groepslijst.
type RepoCard struct {
	Repo    store.Repo
	Stars   int
	Starred bool
	When    string
}

// NoteRow is een reactie in de interface.
type NoteRow struct {
	ID                       int64
	Author, Body, When, Path string
	Start, End               int
	HasSuggestion            bool
}

// DiffFileView is één bestand in de merge-request-diff.
type DiffFileView struct {
	Path  string
	Lines []DiffLineView
}

// DiffLineView is één diffregel, met de reacties die op het nieuwe regelnummer eindigen.
type DiffLineView struct {
	Kind  string
	Text  string
	Old   int
	New   int
	Notes []NoteRow
}

// FileRow is een rij in de bestandstabel of de boom.
type FileRow struct {
	Name, Path, Icon, Subject, When, SHA string
	Dir                                  bool
	Depth                                int
	Active                               bool
}

// CodeLine is één regel broncode.
type CodeLine struct {
	N    int
	HTML template.HTML
}

// CommitRow is een commit in de interface.
// Author is de gekoppelde gebruiker, of anders de ruwe git-naam.
// RawName en PushedBy zijn gezet als de pusher de fallback is en de git-naam afwijkt.
type CommitRow struct {
	SHA, Short, Author, Date, Subject, Body, When string
	UserURL, Avatar, Initial, RawName, PushedBy   string
}

// EntryRow is een bestand of map.
type EntryRow struct {
	Name, Type, Path string
}

// BranchRow is een branch, met of zonder bescherming.
type BranchRow struct {
	Name      string
	Protected bool
}

// HookView is een webhook plus de laatste pogingen.
type HookView struct {
	ID         int64
	Name       string
	Preset     string
	URL        string
	Method     string
	Filter     string
	Events     string
	Deliveries []store.Delivery
}

func repoURL(repo store.Repo) string { return "/" + repo.FullPath() }
