package server

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/cookiejar"
	"net/http/httptest"
	"net/url"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

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

func TestWebhookSecretChoices(t *testing.T) {
	if _, err := exec.LookPath("git"); err != nil {
		t.Skip("git ontbreekt")
	}
	storage := t.TempDir()
	st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = st.Close() })
	cfg := config.Config{
		BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
		Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test"},
		Git:  config.Git{Binary: "git", DefaultBranch: "master"},
	}
	srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true"}
	ts := httptest.NewServer(srv.Handler())
	t.Cleanup(ts.Close)

	jar, _ := cookiejar.New(nil)
	client := &http.Client{Jar: jar}
	res, err := client.Get(ts.URL + "/login")
	if err != nil {
		t.Fatal(err)
	}
	page := read(t, res)
	res, err = client.PostForm(ts.URL+"/new/repo", url.Values{
		"csrf": {csrfOf(t, page)}, "name": {"hooks"}, "visibility": {"private"},
	})
	if err != nil {
		t.Fatal(err)
	}
	_ = read(t, res)

	ctx := context.Background()
	tim, err := st.UserByUsername(ctx, "tim")
	if err != nil {
		t.Fatal(err)
	}
	repo, err := st.RepoByPath(ctx, "tim", "hooks")
	if err != nil {
		t.Fatal(err)
	}
	if err := st.PutSecret(ctx, "repo", repo.ID, "Ada_Webhook", "waarde-niet-tonen", false); err != nil {
		t.Fatal(err)
	}
	g, err := st.CreateGroup(ctx, tim.ID, "Team", "team", "", "developer")
	if err != nil {
		t.Fatal(err)
	}
	if err := st.PutSecret(ctx, "group", g.ID, "GROUP_TOKEN", "groepswaarde", false); err != nil {
		t.Fatal(err)
	}
	grown, err := st.CreateRepo(ctx, "group", g.ID, "app", "", "master", "private")
	if err != nil {
		t.Fatal(err)
	}
	if err := st.PutSecret(ctx, "repo", grown.ID, "Ada_Webhook", "repo-wint", true); err != nil {
		t.Fatal(err)
	}

	res, err = client.Get(ts.URL + "/tim/hooks/-/settings?tab=webhooks")
	if err != nil {
		t.Fatal(err)
	}
	form := read(t, res)
	for _, needle := range []string{
		`name="token"`, `data-secret-button`, `data-secret-filter`, ">None<",
		"Ada_Webhook", "Repository tim/hooks",
	} {
		if !strings.Contains(form, needle) {
			t.Fatalf("formulier mist %q", needle)
		}
	}
	if strings.Contains(form, "waarde-niet-tonen") {
		t.Fatal("geheime waarde op de webhookpagina")
	}
	res, err = client.PostForm(ts.URL+"/tim/hooks/-/secrets", url.Values{
		"csrf": {csrfOf(t, form)}, "name": {"Ada Webhook"}, "value": {"x"},
	})
	if err != nil {
		t.Fatal(err)
	}
	bad := read(t, res)
	if !strings.Contains(bad, `[A-Za-z_][A-Za-z0-9_]*`) || !strings.Contains(bad, "Ada Webhook") {
		t.Fatalf("foutmelding:\n%s", bad)
	}

	res, err = client.Get(ts.URL + "/team/app/-/settings?tab=webhooks")
	if err != nil {
		t.Fatal(err)
	}
	groupForm := read(t, res)
	if !strings.Contains(groupForm, "GROUP_TOKEN") || !strings.Contains(groupForm, "Group team") || !strings.Contains(groupForm, "Ada_Webhook") {
		t.Fatalf("groep en repository:\n%s", groupForm)
	}
	if strings.Contains(groupForm, "groepswaarde") || strings.Contains(groupForm, "repo-wint") {
		t.Fatal("waarde van een overgeërfd geheim op de pagina")
	}

	merged, err := srv.hookSecrets(ctx, "repo", grown.ID, true, grown)
	if err != nil {
		t.Fatal(err)
	}
	if merged["GROUP_TOKEN"] != "groepswaarde" || merged["Ada_Webhook"] != "repo-wint" {
		t.Fatalf("samenvoegen: %#v", merged)
	}
	open, err := srv.hookSecrets(ctx, "repo", grown.ID, false, grown)
	if err != nil {
		t.Fatal(err)
	}
	if _, ok := open["Ada_Webhook"]; ok {
		t.Fatal("beschermd repositorygeheim hoort weg te blijven op een gewone branch")
	}
	if open["GROUP_TOKEN"] != "groepswaarde" {
		t.Fatalf("onbeschermd groepgeheim: %#v", open)
	}

	token, err := st.CreateToken(ctx, tim.ID, "laptop")
	if err != nil {
		t.Fatal(err)
	}
	call := func(method, path, body, auth string) (int, string) {
		t.Helper()
		req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
		if err != nil {
			t.Fatal(err)
		}
		if auth != "" {
			req.Header.Set("Authorization", "Bearer "+auth)
		}
		req.Header.Set("Content-Type", "application/json")
		res, err := client.Do(req)
		if err != nil {
			t.Fatal(err)
		}
		buf := read(t, res)
		return res.StatusCode, buf
	}
	code, body := call(http.MethodGet, "/api/v1/repos/tim/hooks/webhook-secrets", "", "")
	if code != http.StatusUnauthorized {
		t.Fatalf("zonder token %d %s", code, body)
	}
	code, body = call(http.MethodGet, "/api/v1/repos/tim/hooks/webhook-secrets", "", token)
	if code != http.StatusOK || !strings.Contains(body, "Ada_Webhook") || strings.Contains(body, "waarde-niet-tonen") || strings.Contains(body, `"value"`) {
		t.Fatalf("lijst %d %s", code, body)
	}
	var listed struct {
		Secrets []SecretChoice `json:"secrets"`
	}
	if err := json.Unmarshal([]byte(body), &listed); err != nil {
		t.Fatal(err)
	}
	if len(listed.Secrets) != 1 || listed.Secrets[0].Source != "repo" || listed.Secrets[0].Name != "Ada_Webhook" {
		t.Fatalf("keuzes %#v", listed.Secrets)
	}
	code, body = call(http.MethodGet, "/api/v1/groups/team/webhook-secrets", "", token)
	if code != http.StatusOK || !strings.Contains(body, "GROUP_TOKEN") || strings.Contains(body, "groepswaarde") {
		t.Fatalf("groepslijst %d %s", code, body)
	}
	code, body = call(http.MethodGet, "/api/v1/repos/team/app/webhook-secrets", "", token)
	if code != http.StatusOK || !strings.Contains(body, `"source":"group"`) || !strings.Contains(body, `"source":"repo"`) {
		t.Fatalf("overerving %d %s", code, body)
	}
	ada, err := st.UpsertUser(ctx, 2, "ada", "", false)
	if err != nil {
		t.Fatal(err)
	}
	if err := st.SetMember(ctx, "repo", repo.ID, "ada", "developer"); err != nil {
		t.Fatal(err)
	}
	adaTok, err := st.CreateToken(ctx, ada.ID, "ada")
	if err != nil {
		t.Fatal(err)
	}
	code, body = call(http.MethodGet, "/api/v1/repos/tim/hooks/webhook-secrets", "", adaTok)
	if code != http.StatusForbidden {
		t.Fatalf("ontwikkelaar %d %s", code, body)
	}
	raw, _ := json.Marshal(map[string]any{
		"name": "tg", "preset": "telegram", "token": "Ada_Webhook", "chat": "100", "events": []string{"push"},
	})
	code, body = call(http.MethodPost, "/api/v1/repos/tim/hooks/webhooks", string(raw), token)
	if code != http.StatusCreated {
		t.Fatalf("aanmaken %d %s", code, body)
	}
	hooks, err := st.ListWebhooks(ctx, "repo", repo.ID)
	if err != nil {
		t.Fatal(err)
	}
	if len(hooks) != 1 || !strings.Contains(hooks[0].URLTemplate, "{{secret.Ada_Webhook}}") {
		t.Fatalf("webhook %#v", hooks)
	}
	raw, _ = json.Marshal(map[string]any{
		"name": "slecht", "preset": "telegram", "token": "Ada Webhook", "chat": "1", "events": []string{"push"},
	})
	code, body = call(http.MethodPost, "/api/v1/repos/tim/hooks/webhooks", string(raw), token)
	if code != http.StatusBadRequest || !strings.Contains(body, "[A-Za-z_][A-Za-z0-9_]*") {
		t.Fatalf("api-fout %d %s", code, body)
	}
	raw, _ = json.Marshal(map[string]any{
		"name": "ping", "preset": "ntfy", "topic": "builds", "events": []string{"push"},
	})
	code, body = call(http.MethodPost, "/api/v1/groups/team/hooks", string(raw), token)
	if code != http.StatusCreated {
		t.Fatalf("groepshaak %d %s", code, body)
	}
}
