package server

import (
	"bytes"
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

	"gitlab.com/Timfa/bluegit/internal/backupserver/config"
	"gitlab.com/Timfa/bluegit/internal/backupserver/protocol"
)

// fakeBlueGit is een minimale backup-API met bestanden in het geheugen.
type fakeBlueGit struct {
	mu      sync.Mutex
	key     string
	inst    string
	files   map[string]string
	fetches map[string]int
	ts      *httptest.Server
}

func newFake(t *testing.T) *fakeBlueGit {
	f := &fakeBlueGit{key: "bgbk_test", inst: "inst-1", fetches: map[string]int{},
		files: map[string]string{"state/bluegit.db": "db1", "state/secret.key": "k", "data/repos/tim/a.git/HEAD": "ref"}}
	f.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Authorization") != "Bearer "+f.key {
			http.Error(w, `{"error":"key"}`, 401)
			return
		}
		f.mu.Lock()
		defer f.mu.Unlock()
		switch r.URL.Path {
		case "/api/v1/backup/info":
			_ = json.NewEncoder(w).Encode(protocol.Info{InstanceID: f.inst})
		case "/api/v1/backup/connect":
			w.WriteHeader(200)
		case "/api/v1/backup/manifest":
			m := protocol.Manifest{Instance: f.inst}
			for p, c := range f.files {
				e := protocol.Entry{Path: p, Size: int64(len(c)), MTime: int64(len(c)) * 1000, Mode: 0o644}
				if p == protocol.DBPath {
					s := sha256.Sum256([]byte(c))
					e.SHA256 = hex.EncodeToString(s[:])
				}
				m.Files = append(m.Files, e)
			}
			m.Files = append(m.Files, protocol.Entry{Path: "../../etc/passwd", Size: 1})
			_ = json.NewEncoder(w).Encode(m)
		case "/api/v1/backup/file":
			p := r.URL.Query().Get("path")
			c, ok := f.files[p]
			if !ok {
				http.Error(w, `{"error":"weg"}`, 404)
				return
			}
			f.fetches[p]++
			_, _ = io.WriteString(w, c)
		default:
			http.NotFound(w, r)
		}
	}))
	t.Cleanup(f.ts.Close)
	return f
}

func newTestServer(t *testing.T) *Server {
	cfg := config.Config{DataDir: t.TempDir(), PublicURL: "http://backup.test"}
	cfg.Defaults()
	cfg.RateLimitKiB = 0
	s, err := New(cfg, nil)
	if err != nil {
		t.Fatal(err)
	}
	return s
}

func adminReq(s *Server, method, p, body string) *httptest.ResponseRecorder {
	r := httptest.NewRequest(method, p, strings.NewReader(body))
	r.Header.Set("Authorization", "Bearer "+s.AdminToken())
	w := httptest.NewRecorder()
	s.Handler().ServeHTTP(w, r)
	return w
}

func TestSyncIncrementalAndDeletes(t *testing.T) {
	f := newFake(t)
	s := newTestServer(t)
	if w := adminReq(s, "POST", "/api/v1/admin/connect", `{"url":"`+f.ts.URL+`","key":"bgbk_test"}`); w.Code != 200 {
		t.Fatalf("connect %d %s", w.Code, w.Body)
	}
	if _, err := s.SyncNow(context.Background()); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(filepath.Join(s.Cfg.DataDir, "mirror", "data/repos/tim/a.git/HEAD")); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(filepath.Join(s.Cfg.DataDir, "etc", "passwd")); err == nil {
		t.Fatal("pad buiten de kopie geschreven")
	}
	// Ongewijzigd: niets opnieuw. Gewijzigde database: alleen die.
	st, _ := s.SyncNow(context.Background())
	if st.Downloaded != 0 {
		t.Fatalf("tweede sync %+v", st)
	}
	f.mu.Lock()
	f.files["state/bluegit.db"] = "db2"
	delete(f.files, "data/repos/tim/a.git/HEAD")
	f.mu.Unlock()
	st, _ = s.SyncNow(context.Background())
	if st.Downloaded != 1 || st.Deleted != 1 {
		t.Fatalf("derde sync %+v", st)
	}
	if b, _ := os.ReadFile(filepath.Join(s.Cfg.DataDir, "mirror", "state/bluegit.db")); string(b) != "db2" {
		t.Fatalf("db %q", b)
	}
	if _, err := os.Stat(filepath.Join(s.Cfg.DataDir, "mirror", "data/repos/tim")); err == nil {
		t.Fatal("lege map blijft staan")
	}
	// Bestaat state.json en is het 0600 (er staat een key in).
	fi, err := os.Stat(filepath.Join(s.Cfg.DataDir, "state.json"))
	if err != nil || fi.Mode().Perm() != 0o600 {
		t.Fatalf("state.json %v %v", err, fi)
	}
}

func TestSignedEndpoints(t *testing.T) {
	f := newFake(t)
	s := newTestServer(t)
	if w := adminReq(s, "POST", "/api/v1/admin/connect", `{"url":"`+f.ts.URL+`","key":"bgbk_test"}`); w.Code != 200 {
		t.Fatalf("connect %d", w.Code)
	}
	h := s.Handler()
	call := func(method, p, body, secret, inst string) int {
		r := httptest.NewRequest(method, p, bytes.NewReader([]byte(body)))
		if secret != "" {
			protocol.Sign(r, secret, inst, []byte(body), time.Now())
		}
		w := httptest.NewRecorder()
		h.ServeHTTP(w, r)
		return w.Code
	}
	good := protocol.SigningSecret("bgbk_test")
	if c := call("POST", "/api/v1/notify", "{}", "", ""); c != 401 {
		t.Fatalf("zonder handtekening %d", c)
	}
	if c := call("POST", "/api/v1/notify", "{}", protocol.SigningSecret("bgbk_ander"), "inst-1"); c != 401 {
		t.Fatalf("verkeerd geheim %d", c)
	}
	if c := call("POST", "/api/v1/notify", "{}", good, "inst-2"); c != 401 {
		t.Fatalf("andere instantie %d", c)
	}
	if c := call("POST", "/api/v1/notify", "{}", good, "inst-1"); c != 204 {
		t.Fatalf("melding %d", c)
	}
	if c := call("GET", "/api/v1/archives", "", good, "inst-1"); c != 200 {
		t.Fatalf("archieven %d", c)
	}
	if c := call("POST", "/api/v1/rollback", `{"archive":"../x"}`, good, "inst-1"); c != 400 {
		t.Fatalf("ongeldige naam %d", c)
	}
	if c := call("POST", "/api/v1/rollback", `{"archive":"bluegit-20261115-120000.tar.gz"}`, good, "inst-1"); c != 404 {
		t.Fatalf("onbekend archief %d", c)
	}
	// Beheer-API zonder token.
	r := httptest.NewRequest("GET", "/api/v1/admin/status", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	if w.Code != 401 {
		t.Fatalf("status zonder token %d", w.Code)
	}
}

func TestConnectValidation(t *testing.T) {
	f := newFake(t)
	s := newTestServer(t)
	for body, want := range map[string]int{
		`{"url":"ftp://x","key":"bgbk_test"}`:                            400,
		`{"url":"` + f.ts.URL + `","key":"zonder-prefix"}`:               400,
		`{"url":"` + f.ts.URL + `","key":"bgbk_fout"}`:                   401,
		`{"url":"` + f.ts.URL + `","key":"bgbk_test","on_conflict":"x"}`: 400,
	} {
		if w := adminReq(s, "POST", "/api/v1/admin/connect", body); w.Code != want {
			t.Errorf("%s: %d, wil %d (%s)", body, w.Code, want, w.Body)
		}
	}
	s.Cfg.PublicURL = ""
	if w := adminReq(s, "POST", "/api/v1/admin/connect", `{"url":"`+f.ts.URL+`","key":"bgbk_test"}`); w.Code != 400 {
		t.Fatalf("zonder public_url %d", w.Code)
	}
}
