package server

import (
	"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/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/store"
)

func TestPipelineEditorAndProtectedBranch(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", BaseURL: "https://auth.timfalken.com"},
		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)
	tim := &http.Client{Jar: jar}
	res, err := tim.Get(ts.URL + "/login")
	if err != nil {
		t.Fatal(err)
	}
	page := read(t, res)
	res, err = tim.PostForm(ts.URL+"/new/repo", url.Values{
		"csrf": {csrfOf(t, page)}, "name": {"cied"}, "visibility": {"public"},
	})
	if err != nil {
		t.Fatal(err)
	}
	page = read(t, res)
	res, err = tim.PostForm(ts.URL+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"laptop"}})
	if err != nil {
		t.Fatal(err)
	}
	token := between(read(t, res), `<p class="code">`, "</p>")
	remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/cied.git"
	work := t.TempDir()
	git(t, work, "init", "-b", "master")
	git(t, work, "config", "user.email", "tim@users.git.timfalken.com")
	git(t, work, "config", "user.name", "tim")
	yml := "stages:\n  - test\nunit:\n  stage: test\n  image: alpine:3.20\n  script:\n    - echo ok\n"
	writeFile(t, filepath.Join(work, "blue-ci-cd.yml"), yml)
	git(t, work, "add", "blue-ci-cd.yml")
	git(t, work, "commit", "-m", "ci")
	git(t, work, "remote", "add", "origin", remote)
	git(t, work, "push", "-u", "origin", "master")
	git(t, work, "checkout", "-b", "feature")
	git(t, work, "push", "-u", "origin", "feature")

	res, err = tim.Get(ts.URL + "/tim/cied/-/ci/editor?ref=feature")
	if err != nil {
		t.Fatal(err)
	}
	editor := read(t, res)
	for _, want := range []string{"Pipeline Editor", "No issues found", "echo ok", "ci-gutter", "Commit message"} {
		if !strings.Contains(editor, want) {
			t.Errorf("editor mist %q", want)
		}
	}
	csrf := csrfOf(t, editor)
	res, err = tim.PostForm(ts.URL+"/tim/cied/-/ci/lint", url.Values{
		"csrf": {csrf}, "ref": {"feature"}, "body": {"stages: [\n"},
	})
	if err != nil {
		t.Fatal(err)
	}
	raw := read(t, res)
	var lint struct {
		Status      string `json:"status"`
		StatusClass string `json:"statusClass"`
		Issues      []struct {
			Line int    `json:"line"`
			Text string `json:"text"`
		} `json:"issues"`
	}
	if err := json.Unmarshal([]byte(raw), &lint); err != nil {
		t.Fatalf("lint json: %v\n%s", err, raw)
	}
	if lint.StatusClass != "failed" || len(lint.Issues) == 0 || strings.Count(lint.Issues[0].Text, "invalid YAML") != 1 {
		t.Fatalf("lint: %+v", lint)
	}

	changed := "stages:\n  - test\nunit:\n  stage: test\n  image: alpine:3.20\n  script:\n    - echo changed\n"
	res, err = tim.PostForm(ts.URL+"/tim/cied/-/ci/editor", url.Values{
		"csrf": {csrf}, "base": {"feature"}, "branch": {"feature"}, "message": {"pas de editor aan"}, "body": {changed},
	})
	if err != nil {
		t.Fatal(err)
	}
	saved := read(t, res)
	if !strings.Contains(saved, "Committed.") || !strings.Contains(saved, "echo changed") {
		t.Fatalf("na commit:\n%s", saved)
	}
	dir := gitrepo.Dir(storage, "tim", "cied")
	if got := mustGit(t, dir, "show", "feature:blue-ci-cd.yml"); !strings.Contains(got, "echo changed") {
		t.Fatalf("bestand: %s", got)
	}
	if msg := mustGit(t, dir, "log", "-1", "--format=%s", "feature"); strings.TrimSpace(msg) != "pas de editor aan" {
		t.Fatalf("bericht: %s", msg)
	}

	res, err = tim.PostForm(ts.URL+"/tim/cied/-/ci/editor", url.Values{
		"csrf": {csrfOf(t, saved)}, "base": {"feature"}, "branch": {"ci-try"}, "message": {"nieuwe branch"}, "body": {changed},
	})
	if err != nil {
		t.Fatal(err)
	}
	_ = read(t, res)
	if got := mustGit(t, dir, "show", "ci-try:blue-ci-cd.yml"); !strings.Contains(got, "echo changed") {
		t.Fatalf("nieuwe branch: %s", got)
	}

	ctx := res.Request.Context()
	repo, err := st.RepoByPath(ctx, "tim", "cied")
	if err != nil {
		t.Fatal(err)
	}
	ada, err := st.UpsertUser(ctx, 3, "ada", "", false)
	if err != nil {
		t.Fatal(err)
	}
	if err := st.SetMember(ctx, "repo", repo.ID, "ada", "developer"); err != nil {
		t.Fatal(err)
	}
	adaC := clientAs(t, ts.URL, st, ada.ID)
	res, err = adaC.Get(ts.URL + "/tim/cied/-/ci/editor?ref=master")
	if err != nil {
		t.Fatal(err)
	}
	adaPage := read(t, res)
	res, err = adaC.PostForm(ts.URL+"/tim/cied/-/ci/editor", url.Values{
		"csrf": {csrfOf(t, adaPage)}, "base": {"master"}, "branch": {"master"}, "message": {"ada op master"}, "body": {changed + "\n"},
	})
	if err != nil {
		t.Fatal(err)
	}
	denied := read(t, res)
	if !strings.Contains(denied, "This branch is protected.") {
		t.Fatalf("beschermd:\n%s", denied)
	}
	if got := mustGit(t, dir, "show", "master:blue-ci-cd.yml"); strings.Contains(got, "echo changed") {
		t.Fatalf("master veranderde:\n%s", got)
	}
}
