package server

import (
	"io"
	"net/http"
	"net/http/cookiejar"
	"net/http/httptest"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
	"time"

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

func TestBranchIsStale(t *testing.T) {
	now := time.Date(2026, 10, 23, 12, 0, 0, 0, time.UTC)
	old := now.Add(-91 * 24 * time.Hour).Unix()
	fresh := now.Add(-10 * 24 * time.Hour).Unix()
	if !branchIsStale(old, false, now) {
		t.Fatal("een branch zonder commit in drie maanden is inactief")
	}
	if branchIsStale(old, true, now) {
		t.Fatal("de standaardbranch blijft actief")
	}
	if branchIsStale(fresh, false, now) {
		t.Fatal("een recente branch is actief")
	}
	if branchIsStale(0, false, now) {
		t.Fatal("een branch zonder datum is actief")
	}
}

func TestBranchGroupsAndArchive(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"))
	page = read(t, mustPost(t, tim, ts.URL+"/new/repo", url.Values{
		"csrf": {csrfOf(t, page)}, "name": {"groepen"}, "visibility": {"public"},
	}))
	page = read(t, mustPost(t, tim, ts.URL+"/settings/tokens", url.Values{
		"csrf": {csrfOf(t, page)}, "name": {"laptop"},
	}))
	token := between(page, `<p class="code">`, "</p>")
	remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/groepen.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")
	writeFile(t, filepath.Join(work, "hello.txt"), "alpha\n")
	git(t, work, "add", "hello.txt")
	git(t, work, "commit", "-m", "start")
	git(t, work, "remote", "add", "origin", remote)
	git(t, work, "push", "-u", "origin", "master")

	git(t, work, "checkout", "-b", "vers")
	writeFile(t, filepath.Join(work, "hello.txt"), "beta\n")
	git(t, work, "add", "hello.txt")
	git(t, work, "commit", "-m", "vers-onderwerp")
	git(t, work, "push", "-u", "origin", "vers")

	git(t, work, "checkout", "-b", "oud", "master")
	writeFile(t, filepath.Join(work, "hello.txt"), "oud\n")
	git(t, work, "add", "hello.txt")
	commitAt(t, work, "oud-onderwerp", "2020-01-15T12:00:00")
	git(t, work, "push", "-u", "origin", "oud")

	overview := read(t, mustGet(t, tim, ts.URL+"/tim/groepen/-/branches"))
	for _, want := range []string{
		`class="on"`, "Overview", "Active branches", "Stale branches",
		`data-name="master"`, `data-name="vers"`, `data-name="oud"`,
		"Filter by branch name", "New branch", "default",
		`data-copy="oud"`, "Create MR", "vers-onderwerp", "oud-onderwerp",
		"/-/branches/archive?name=oud&amp;format=zip",
		"/-/branches/archive?name=oud&amp;format=tar.gz",
		"/-/merge-requests/new?source=oud&amp;target=master",
	} {
		if !strings.Contains(overview, want) {
			t.Fatalf("overzicht mist %q", want)
		}
	}
	if strings.Contains(overview, `data-delete="master"`) {
		t.Fatal("de standaardbranch heeft een verwijderknop")
	}
	if !strings.Contains(overview, `data-delete="oud"`) || !strings.Contains(overview, `data-delete="vers"`) {
		t.Fatal("een gewone branch mist de verwijderknop")
	}
	oudAt := strings.Index(overview, `data-name="oud"`)
	staleAt := strings.Index(overview, "Stale branches")
	activeAt := strings.Index(overview, "Active branches")
	if activeAt < 0 || staleAt < activeAt || oudAt < staleAt {
		t.Fatalf("oud hoort in de inactieve groep:\n%s", overview)
	}

	active := read(t, mustGet(t, tim, ts.URL+"/tim/groepen/-/branches?state=active"))
	if strings.Contains(active, `data-name="oud"`) || strings.Contains(active, "Stale branches") || !strings.Contains(active, `data-name="master"`) {
		t.Fatalf("actief:\n%s", active)
	}
	stale := read(t, mustGet(t, tim, ts.URL+"/tim/groepen/-/branches?state=stale"))
	if !strings.Contains(stale, `data-name="oud"`) || strings.Contains(stale, `data-name="master"`) || strings.Contains(stale, "Active branches") {
		t.Fatalf("inactief:\n%s", stale)
	}
	if !strings.Contains(stale, `state=stale"`) || !strings.Contains(stale, `class="on"`) {
		t.Fatalf("tab inactief:\n%s", stale)
	}

	zipRes := mustGet(t, tim, ts.URL+"/tim/groepen/-/branches/archive?name=oud&format=zip")
	zipBody, err := io.ReadAll(zipRes.Body)
	zipRes.Body.Close()
	if err != nil {
		t.Fatal(err)
	}
	if zipRes.StatusCode != http.StatusOK || len(zipBody) < 2 || zipBody[0] != 'P' || zipBody[1] != 'K' {
		t.Fatalf("zip status %d lengte %d", zipRes.StatusCode, len(zipBody))
	}
	if !strings.Contains(zipRes.Header.Get("Content-Disposition"), "groepen-oud.zip") {
		t.Fatalf("bestandsnaam: %s", zipRes.Header.Get("Content-Disposition"))
	}
	tarRes := mustGet(t, tim, ts.URL+"/tim/groepen/-/branches/archive?name=vers&format=tar.gz")
	tarBody, err := io.ReadAll(tarRes.Body)
	tarRes.Body.Close()
	if err != nil {
		t.Fatal(err)
	}
	if tarRes.StatusCode != http.StatusOK || len(tarBody) < 2 || tarBody[0] != 0x1f || tarBody[1] != 0x8b {
		t.Fatalf("tar.gz status %d", tarRes.StatusCode)
	}
	missing := mustGet(t, tim, ts.URL+"/tim/groepen/-/branches/archive?name=geen&format=zip")
	missing.Body.Close()
	if missing.StatusCode != http.StatusNotFound {
		t.Fatalf("ontbrekende branch: %d", missing.StatusCode)
	}
	bad := mustGet(t, tim, ts.URL+"/tim/groepen/-/branches/archive?name=master&format=exe")
	bad.Body.Close()
	if bad.StatusCode != http.StatusNotFound {
		t.Fatalf("formaat: %d", bad.StatusCode)
	}
}

func commitAt(t *testing.T, dir, msg, when string) {
	t.Helper()
	cmd := exec.Command("git", "-c", "commit.gpgsign=false", "commit", "-m", msg)
	cmd.Dir = dir
	cmd.Env = append(os.Environ(), "GIT_AUTHOR_DATE="+when, "GIT_COMMITTER_DATE="+when)
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("commit: %v\n%s", err, out)
	}
}
