package server

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

	"gitlab.com/Timfa/bluegit/internal/access"
	"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 TestPipelineRetryButtonAndAPI(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}
	page := read(t, mustGet(t, tim, ts.URL+"/login"))
	if _, err := tim.PostForm(ts.URL+"/new/repo", url.Values{
		"csrf": {csrfOf(t, page)}, "name": {"opnieuw"}, "visibility": {"public"},
	}); err != nil {
		t.Fatal(err)
	}
	ctx := context.Background()
	repo, err := st.RepoByPath(ctx, "tim", "opnieuw")
	if err != nil {
		t.Fatal(err)
	}
	ro, err := st.UpsertUser(ctx, 2, "ro", "", false)
	if err != nil {
		t.Fatal(err)
	}
	if err := st.SetMember(ctx, "repo", repo.ID, "ro", access.RoleReadonly); err != nil {
		t.Fatal(err)
	}
	roToken, err := st.CreateToken(ctx, ro.ID, "ro")
	if err != nil {
		t.Fatal(err)
	}
	owner, err := st.UserByUsername(ctx, "tim")
	if err != nil {
		t.Fatal(err)
	}
	ownerToken, err := st.CreateToken(ctx, owner.ID, "tim")
	if err != nil {
		t.Fatal(err)
	}

	dir := gitrepo.Dir(storage, "tim", "opnieuw")
	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")
	writeFile(t, filepath.Join(work, "README.md"), "hallo\n")
	git(t, work, "add", "README.md")
	git(t, work, "commit", "-m", "leesmij")
	git(t, work, "remote", "add", "origin", dir)
	git(t, work, "push", "origin", "master")
	sha := strings.TrimSpace(mustGit(t, dir, "rev-parse", "refs/heads/master"))
	git(t, dir, "branch", "topic", sha)

	mr, err := st.CreateMergeRequest(ctx, repo.ID, owner.ID, "Opnieuw", "", "topic", "master")
	if err != nil {
		t.Fatal(err)
	}
	okID := makePipe(t, st, repo.ID, sha, "groen", []store.NewJob{
		{Name: "lint", Stage: "test", Script: "exit 0"},
	})
	finishPipe(t, st, okID, "success")
	id := makePipe(t, st, repo.ID, sha, "rood", []store.NewJob{
		{Name: "lint", Stage: "test", Script: "exit 0"},
		{Name: "unit", Stage: "test", Script: "exit 1"},
		{Name: "pack", Stage: "deploy", Script: "exit 0"},
		{Name: "pages", Stage: "deploy", Script: "exit 0", When: "manual"},
		{Name: "aur", Stage: "deploy", Script: "echo aur", NeedsSet: true},
		{Name: "note", Stage: "deploy", Script: "exit 0"},
	})
	jobs, err := st.JobsByPipeline(ctx, id)
	if err != nil {
		t.Fatal(err)
	}
	for _, j := range jobs {
		switch j.Name {
		case "lint", "aur":
			if err := st.FinishJob(ctx, j.ID, "success", "ok\n"); err != nil {
				t.Fatal(err)
			}
		case "unit":
			if err := st.FinishJob(ctx, j.ID, "failed", "nee\n"); err != nil {
				t.Fatal(err)
			}
		case "note":
			if err := st.FinishJob(ctx, j.ID, "canceled", "stop\n"); err != nil {
				t.Fatal(err)
			}
		case "pack", "pages":
			if err := st.SkipJob(ctx, j.ID, "skipped\n"); err != nil {
				t.Fatal(err)
			}
		}
	}
	if _, err := st.RefreshPipelineStatus(ctx, id); err != nil {
		t.Fatal(err)
	}
	if err := st.AttachPipelineMR(ctx, id, mr.ID); err != nil {
		t.Fatal(err)
	}

	list := read(t, mustGet(t, tim, ts.URL+"/tim/opnieuw/-/pipelines"))
	detail := read(t, mustGet(t, tim, ts.URL+"/tim/opnieuw/-/pipelines/"+strconv.FormatInt(id, 10)))
	home := read(t, mustGet(t, tim, ts.URL+"/tim/opnieuw"))
	mrPage := read(t, mustGet(t, tim, ts.URL+"/tim/opnieuw/-/merge-requests/1"))
	for _, body := range []string{list, detail, home, mrPage} {
		if !strings.Contains(body, `class="rowmenu piperetry"`) || !strings.Contains(body, "Retry entire pipeline") {
			t.Fatalf("schrijver mist de knop:\n%s", body)
		}
	}
	failedForm := `data-retry-failed data-pipe="` + strconv.FormatInt(id, 10) + `"`
	okForm := `data-retry-failed data-pipe="` + strconv.FormatInt(okID, 10) + `" hidden`
	if !strings.Contains(list, failedForm) || strings.Contains(list, failedForm+" hidden") || !strings.Contains(list, okForm) {
		t.Fatalf("mislukte optie hoort alleen bij de rode pipeline:\n%s", list)
	}
	if !strings.Contains(detail, "Retry failed jobs") || strings.Contains(detail, failedForm+" hidden") {
		t.Fatalf("detail mist de mislukte optie:\n%s", detail)
	}
	if !strings.Contains(home, "Retry failed jobs") || !strings.Contains(mrPage, "Retry failed jobs") {
		t.Fatal("overzicht of merge request mist de mislukte optie")
	}

	anon := read(t, mustGet(t, http.DefaultClient, ts.URL+"/tim/opnieuw/-/pipelines"))
	anonHome := read(t, mustGet(t, http.DefaultClient, ts.URL+"/tim/opnieuw"))
	anonMR := read(t, mustGet(t, http.DefaultClient, ts.URL+"/tim/opnieuw/-/merge-requests/1"))
	anonDetail := read(t, mustGet(t, http.DefaultClient, ts.URL+"/tim/opnieuw/-/pipelines/"+strconv.FormatInt(id, 10)))
	for _, body := range []string{anon, anonHome, anonMR, anonDetail} {
		if strings.Contains(body, "piperetry") || strings.Contains(body, "Retry entire pipeline") {
			t.Fatalf("lezer ziet de knop:\n%s", body)
		}
	}

	code, body := retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", roToken, `{"mode":"failed"}`)
	if code != 403 {
		t.Fatalf("readonly api %d %s", code, body)
	}
	code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, `{"mode":"nope"}`)
	if code != 400 {
		t.Fatalf("mode %d %s", code, body)
	}
	res, err := http.PostForm(ts.URL+"/tim/opnieuw/-/pipelines/"+strconv.FormatInt(id, 10)+"/retry", url.Values{"mode": {"all"}})
	if err != nil {
		t.Fatal(err)
	}
	if res.StatusCode != http.StatusForbidden {
		t.Fatalf("anonieme post %d", res.StatusCode)
	}
	res.Body.Close()

	csrf := csrfOf(t, detail)
	done := read(t, mustPost(t, tim, ts.URL+"/tim/opnieuw/-/pipelines/"+strconv.FormatInt(id, 10)+"/retry", url.Values{
		"csrf": {csrf}, "mode": {"failed"}, "back": {"/tim/opnieuw/-/pipelines/" + strconv.FormatInt(id, 10)},
	}))
	if !strings.Contains(done, "Pipeline retried") || !strings.Contains(done, "Running") {
		t.Fatalf("na mislukte jobs:\n%s", done)
	}
	if !strings.Contains(done, failedForm+" hidden") {
		t.Fatalf("optie blijft staan zonder mislukking:\n%s", done)
	}
	got := map[string]string{}
	jobs, err = st.JobsByPipeline(ctx, id)
	if err != nil {
		t.Fatal(err)
	}
	for _, j := range jobs {
		got[j.Name] = j.Status
	}
	if got["lint"] != "success" || got["aur"] != "success" || got["unit"] != "queued" || got["pack"] != "queued" || got["pages"] != "manual" || got["note"] != "canceled" {
		t.Fatalf("jobs na retry: %v", got)
	}
	p, err := st.PipelineByID(ctx, repo.ID, id)
	if err != nil || p.Status != "running" {
		t.Fatalf("pipelinestatus %s %v", p.Status, err)
	}

	code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, `{"mode":"failed"}`)
	if code != 409 {
		t.Fatalf("tweede failed %d %s", code, body)
	}
	code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, `{}`)
	if code != 409 {
		t.Fatalf("leeg object default failed %d %s", code, body)
	}
	code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, "")
	if code != 409 {
		t.Fatalf("lege body default failed %d %s", code, body)
	}
	// Zonder gefaalde job weigert ook "all" (zelfde regel als de UI).
	for _, pid := range []int64{id, okID} {
		code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(pid, 10)+"/retry", ownerToken, `{"mode":"all"}`)
		if code != 409 || !strings.Contains(body, "no failed jobs") {
			t.Fatalf("all zonder mislukking %d: %d %s", pid, code, body)
		}
	}
	if !strings.Contains(read(t, mustGet(t, tim, ts.URL+"/tim/opnieuw/-/pipelines/"+strconv.FormatInt(okID, 10))), okForm) {
		t.Fatal("geslaagde pipeline toont retry")
	}
	jobs, _ = st.JobsByPipeline(ctx, id)
	for _, j := range jobs {
		if j.Name == "unit" {
			if err := st.FinishJob(ctx, j.ID, "failed", "runner_system_failure: weg\n"); err != nil {
				t.Fatal(err)
			}
		}
	}
	code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, `{"mode":"all"}`)
	if code != 201 {
		t.Fatalf("all %d %s", code, body)
	}
	var created map[string]any
	if err := json.Unmarshal([]byte(body), &created); err != nil {
		t.Fatal(err)
	}
	newID, _ := created["id"].(float64)
	if int64(newID) == id || created["sha"] != sha || created["source"] != "push" && created["source"] != "merge_request_event" {
		t.Fatalf("antwoord %s", body)
	}
	clone, err := st.PipelineByID(ctx, repo.ID, int64(newID))
	if err != nil {
		t.Fatal(err)
	}
	if clone.CommitSHA != sha || clone.Ref != "refs/heads/master" || clone.Source != "push" || clone.MRID != mr.ID || clone.Status != "queued" {
		t.Fatalf("kloon %+v", clone)
	}
	old, err := st.PipelineByID(ctx, repo.ID, id)
	if err != nil || old.Status != "running" {
		t.Fatalf("oude pipeline %s %v", old.Status, err)
	}
}

func retryAPI(t *testing.T, ts *httptest.Server, method, path, token, body string) (int, string) {
	t.Helper()
	req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
	if err != nil {
		t.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+token)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	raw, err := io.ReadAll(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	return res.StatusCode, string(raw)
}
