package server

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"

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

type actorKey struct{}

type apiActor struct {
	User   store.User
	Scopes access.Scopes
	Via    string
	// JobRepo is de repo van een lopende job (Via "job"); alleen die mag hij lezen.
	JobRepo int64
}

type apiAuth int

const (
	authUser apiAuth = iota
	authPublic
	authRelease
	authOptional
)

type apiHandler func(*Server, http.ResponseWriter, *http.Request)

type apiRoute struct {
	Method  string
	Path    string
	Class   access.ScopeClass
	Auth    apiAuth
	Summary string
	Handler apiHandler
}

// apiRouteTaken zegt of server.go die methode en dat pad al registreert.
// ServeMux weigert hetzelfde patroon twee keer. De expliciete handlers
// blijven, de catalogus noemt het pad nog voor OpenAPI.
func apiRouteTaken(method, path string) bool {
	switch method + " " + path {
	case "POST /api/v1/repos/{owner}/{repo}/releases",
		"GET /api/v1/groups/{path}/secrets",
		"POST /api/v1/groups/{path}/secrets",
		"DELETE /api/v1/groups/{path}/secrets/{name}",
		"GET /api/v1/repos/{owner}/{repo}/issues",
		"POST /api/v1/repos/{owner}/{repo}/issues",
		"GET /api/v1/repos/{owner}/{repo}/issues/{number}",
		"PUT /api/v1/repos/{owner}/{repo}/issues/{number}",
		"DELETE /api/v1/repos/{owner}/{repo}/issues/{number}",
		"POST /api/v1/repos/{owner}/{repo}/issues/{number}/notes":
		return true
	default:
		return false
	}
}

func (s *Server) mountAPI(mux *http.ServeMux) {
	mux.HandleFunc("GET /api/v1/openapi.json", func(w http.ResponseWriter, r *http.Request) {
		s.serveAPI(w, r, apiRoute{Method: http.MethodGet, Path: "/api/v1/openapi.json", Class: access.ScopePublic, Auth: authPublic, Summary: "OpenAPI document", Handler: (*Server).openAPI})
	})
	for _, rt := range apiCatalog {
		rt := rt
		if apiRouteTaken(rt.Method, rt.Path) {
			continue
		}
		mux.HandleFunc(rt.Method+" "+rt.Path, func(w http.ResponseWriter, r *http.Request) {
			s.serveAPI(w, r, rt)
		})
	}
}

func (s *Server) serveAPI(w http.ResponseWriter, r *http.Request, rt apiRoute) {
	w.Header().Set("Cache-Control", "no-store")
	if rt.Auth == authPublic {
		rt.Handler(s, w, r)
		return
	}
	if rt.Auth == authRelease {
		tok := tokenFrom(r)
		if strings.HasPrefix(tok, "bgj_") {
			rt.Handler(s, w, r)
			return
		}
	}
	if tok := tokenFrom(r); strings.HasPrefix(tok, "bgj_") {
		s.serveJobAPI(w, r, rt, tok)
		return
	}
	actor, ok := r.Context().Value(actorKey{}).(apiActor)
	if !ok {
		tok := tokenFrom(r)
		if tok == "" && rt.Auth == authOptional {
			rt.Handler(s, w, r)
			return
		}
		if tok == "" || !strings.HasPrefix(tok, "bg_") {
			s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.apiAuth")))
			return
		}
		auth, err := s.Store.AuthenticateToken(r.Context(), tok)
		if err != nil {
			s.writeAPIErr(w, r, fail(http.StatusUnauthorized, err))
			return
		}
		actor = apiActor{User: auth.User, Scopes: access.StoredScopes(auth.Token.Scopes), Via: "token"}
	}
	if !actor.Scopes.Allows(rt.Class) {
		s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.apiScope")))
		return
	}
	ctx := context.WithValue(r.Context(), ctxKey{}, principal{User: actor.User, OK: true})
	ctx = context.WithValue(ctx, actorKey{}, actor)
	rt.Handler(s, w, r.WithContext(ctx))
}

func tokenFrom(r *http.Request) string {
	if t := strings.TrimSpace(r.Header.Get("PRIVATE-TOKEN")); t != "" {
		return t
	}
	if t := bearer(r); t != "" {
		return t
	}
	_, pass, ok := r.BasicAuth()
	if ok {
		return pass
	}
	return ""
}

func apiUser(r *http.Request) store.User {
	a, _ := r.Context().Value(actorKey{}).(apiActor)
	return a.User
}

func readJSON(r *http.Request, dst any) error {
	if r.Body == nil {
		return nil
	}
	dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
	err := dec.Decode(dst)
	if err == io.EOF {
		return nil
	}
	return err
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	if status == http.StatusNoContent {
		w.WriteHeader(status)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

func (s *Server) writeAPIErr(w http.ResponseWriter, r *http.Request, err error) {
	writeJSON(w, statusOf(err), map[string]any{"message": s.trErr(r, err)})
}

func (s *Server) apiOK(w http.ResponseWriter, r *http.Request, err error) bool {
	if err == nil {
		return true
	}
	s.writeAPIErr(w, r, err)
	return false
}

func pageQuery(r *http.Request) (page, per int) {
	page, _ = strconv.Atoi(r.URL.Query().Get("page"))
	per, _ = strconv.Atoi(r.URL.Query().Get("per_page"))
	if page < 1 {
		page = 1
	}
	if per < 1 {
		per = 20
	}
	if per > 100 {
		per = 100
	}
	return page, per
}

func writePage(w http.ResponseWriter, r *http.Request, items any, total, page, per int) {
	w.Header().Set("X-Total", strconv.Itoa(total))
	w.Header().Set("X-Page", strconv.Itoa(page))
	w.Header().Set("X-Per-Page", strconv.Itoa(per))
	next := ""
	if page*per < total {
		next = strconv.Itoa(page + 1)
	}
	w.Header().Set("X-Next-Page", next)
	writeJSON(w, http.StatusOK, items)
}

func slicePage[T any](items []T, page, per int) []T {
	if items == nil {
		items = []T{}
	}
	start := (page - 1) * per
	if start > len(items) {
		start = len(items)
	}
	end := start + per
	if end > len(items) {
		end = len(items)
	}
	out := items[start:end]
	if out == nil {
		out = []T{}
	}
	return out
}

// CallAPI voert een API-verzoek uit als deze gebruiker, zonder cookie.
// SSH gebruikt hetzelfde pad als een toegangstoken met scope api.
func (s *Server) CallAPI(ctx context.Context, user store.User, method, path string, body []byte) (int, []byte) {
	if !strings.HasPrefix(path, "/") {
		path = "/" + path
	}
	if !strings.HasPrefix(path, "/api/") {
		path = "/api/v1" + path
	}
	var rdr io.Reader = http.NoBody
	if len(body) > 0 {
		rdr = bytes.NewReader(body)
	}
	req := httptest.NewRequest(method, path, rdr).WithContext(context.WithValue(ctx, actorKey{}, apiActor{
		User: user, Scopes: access.AllScopes(), Via: "ssh",
	}))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	s.Handler().ServeHTTP(rec, req)
	return rec.Code, rec.Body.Bytes()
}

func (s *Server) openAPI(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, openAPIDoc())
}

func openAPIDoc() map[string]any {
	paths := map[string]map[string]any{}
	for _, rt := range apiCatalog {
		rel := strings.TrimPrefix(rt.Path, "/api/v1")
		rel = openAPIPath(rel)
		item := paths[rel]
		if item == nil {
			item = map[string]any{}
			paths[rel] = item
		}
		op := map[string]any{
			"summary":   rt.Summary,
			"responses": map[string]any{"200": map[string]any{"description": "OK"}, "default": map[string]any{"description": "Error", "content": map[string]any{"application/json": map[string]any{"schema": map[string]any{"$ref": "#/components/schemas/Error"}}}}},
		}
		switch rt.Auth {
		case authPublic:
		case authOptional:
			op["description"] = "Public. Without a token the viewer is anonymous and only sees public repositories and groups. A valid token includes private items that account may see. Contributions follow the same filter."
			op["security"] = []any{
				map[string]any{},
				map[string]any{"bearer": []any{}},
				map[string]any{"privateToken": []any{}},
				map[string]any{"basic": []any{}},
			}
		default:
			op["security"] = []any{
				map[string]any{"bearer": []any{}},
				map[string]any{"privateToken": []any{}},
				map[string]any{"basic": []any{}},
			}
		}
		item[strings.ToLower(rt.Method)] = op
	}
	schemas := map[string]any{
		"Error": map[string]any{"type": "object", "properties": map[string]any{"message": map[string]any{"type": "string"}}},
	}
	decorateAPI(paths, schemas)
	paths["/openapi.json"] = map[string]any{
		"get": map[string]any{"summary": "OpenAPI document", "responses": map[string]any{"200": map[string]any{"description": "OK"}}},
	}
	out := map[string]any{}
	for k, v := range paths {
		out[k] = v
	}
	return map[string]any{
		"openapi": "3.0.3",
		"info":    map[string]any{"title": "BlueGit", "version": "v1"},
		"servers": []any{map[string]any{"url": "/api/v1"}},
		"paths":   out,
		"components": map[string]any{
			"securitySchemes": map[string]any{
				"bearer":       map[string]any{"type": "http", "scheme": "bearer"},
				"privateToken": map[string]any{"type": "apiKey", "in": "header", "name": "PRIVATE-TOKEN"},
				"basic":        map[string]any{"type": "http", "scheme": "basic"},
			},
			"schemas": schemas,
		},
	}
}

func openAPIPath(p string) string {
	var b strings.Builder
	for i := 0; i < len(p); i++ {
		if p[i] == '{' {
			j := strings.IndexByte(p[i:], '}')
			if j < 0 {
				b.WriteByte(p[i])
				continue
			}
			name := p[i+1 : i+j]
			name = strings.TrimSuffix(name, "...")
			b.WriteByte('{')
			b.WriteString(name)
			b.WriteByte('}')
			i += j
			continue
		}
		b.WriteByte(p[i])
	}
	return b.String()
}

func apiIndex() []byte {
	type row struct {
		Method  string `json:"method"`
		Path    string `json:"path"`
		Summary string `json:"summary"`
		Auth    string `json:"auth"`
	}
	routes := []row{{Method: http.MethodGet, Path: "/api/v1/openapi.json", Summary: "OpenAPI document", Auth: "public"}}
	for _, rt := range apiCatalog {
		auth := "token"
		switch rt.Auth {
		case authPublic:
			auth = "public"
		case authRelease:
			auth = "token_or_job"
		case authOptional:
			auth = "public_or_token"
		}
		routes = append(routes, row{Method: rt.Method, Path: rt.Path, Summary: rt.Summary, Auth: auth})
	}
	raw, _ := json.Marshal(map[string]any{
		"openapi": "/api/v1/openapi.json",
		"auth":    []string{"Authorization: Bearer", "PRIVATE-TOKEN", "HTTP basic"},
		"scopes":  []string{access.ScopeAPI, access.ScopeReadAPI, access.ScopeReadRepo, access.ScopeWriteRepo},
		"ssh":     "ssh git@host api METHOD /api/v1/... ",
		"routes":  routes,
	})
	return raw
}

// serveJobAPI laat een job-token alleen GET-routes van de eigen repo lezen,
// met de rechten van een leesrol. Al het andere is 401.
func (s *Server) serveJobAPI(w http.ResponseWriter, r *http.Request, rt apiRoute, tok string) {
	deny := func() { s.writeAPIErr(w, r, fail(http.StatusUnauthorized, i18n.E("err.jobToken"))) }
	if r.Method != http.MethodGet || !strings.Contains(rt.Path, "{owner}/{repo}") {
		deny()
		return
	}
	job, err := s.Store.JobByToken(r.Context(), tok)
	if err != nil || job.Status != "running" {
		deny()
		return
	}
	repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
	if err != nil || repo.ID != job.RepoID {
		deny()
		return
	}
	actor := apiActor{Scopes: access.StoredScopes(access.ScopeReadAPI + "," + access.ScopeReadRepo), Via: "job", JobRepo: job.RepoID}
	if !actor.Scopes.Allows(rt.Class) {
		s.writeAPIErr(w, r, fail(http.StatusForbidden, i18n.E("err.apiScope")))
		return
	}
	ctx := context.WithValue(r.Context(), ctxKey{}, principal{OK: false})
	ctx = context.WithValue(ctx, actorKey{}, actor)
	rt.Handler(s, w, r.WithContext(ctx))
}

// jobRole geeft een leesrol als de API-aanroep van een job voor de eigen repo is.
func jobRole(r *http.Request, repoID int64) access.Role {
	if a, ok := r.Context().Value(actorKey{}).(apiActor); ok && a.Via == "job" && a.JobRepo == repoID {
		return access.RoleReadonly
	}
	return access.RoleNone
}
