// 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"
	"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/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
	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

	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/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 /groups/{path}", s.groupPage)
	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}/notes", s.createNote)
	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}/-/releases", s.releases)
	mux.HandleFunc("GET /{owner}/{repo}/-/releases/{tag}/assets/{name}", s.releaseAsset)
	mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
	mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
	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.tmpl != nil {
		return
	}
	s.tmpl = 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") },
	}).ParseFS(webFS, "templates/*.html"))
}

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, "ongeldig formulier", http.StatusBadRequest)
		return false
	}
	p := s.who(r)
	if !p.OK || r.FormValue("csrf") == "" || r.FormValue("csrf") != p.Session.CSRF {
		http.Error(w, "ongeldig formulier, vernieuw de pagina", 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: notice, Path: "/", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
	}
	if problem != "" {
		http.SetCookie(w, &http.Cookie{Name: "bluegit_error", Value: 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 := cookieVal(r, "bluegit_notice"), cookieVal(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 (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) view(w http.ResponseWriter, r *http.Request, title string) View {
	notice, problem := s.takeFlash(w, r)
	v := View{Title: title, BaseURL: s.Cfg.BaseURL, Notice: notice, Err: problem, StorageUnset: s.StoragePath() == ""}
	if p := s.who(r); p.OK {
		u := p.User
		v.User = &u
		v.CSRF = p.Session.CSRF
	}
	return v
}

func (s *Server) render(w http.ResponseWriter, name string, v View) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := s.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
	Commits      []CommitRow
	Commit       *CommitRow
	Entries      []EntryRow
	TreePath     string
	Blob         string
	BlobPath     string
	Binary       bool
	Branches     []BranchRow
	MRs          []store.MergeRequest
	MR           *store.MergeRequest
	Diff         string
	Pipes        []store.Pipeline
	Pipe         *store.Pipeline
	Jobs         []store.Job
	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
	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
}

// NoteRow is een reactie in de interface.
type NoteRow struct {
	Author, Body, When string
}

// 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.
type CommitRow struct {
	SHA, Short, Author, Date, Subject, Body, When 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
	Filter     string
	Events     string
	Deliveries []store.Delivery
}

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