package server

import (
	"context"
	"encoding/json"
	"net/http"
	"strings"
	"testing"
	"time"

	"gitlab.com/Timfa/bluegit/internal/store"
	"gitlab.com/Timfa/bluegit/internal/update"
)

func postUpdate(t *testing.T, url, token, body string) (int, string) {
	t.Helper()
	req, _ := http.NewRequest(http.MethodPost, url+"/api/v1/admin/self-update", strings.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	return res.StatusCode, read(t, res)
}

func TestUpdateGateHoldsNewPipelines(t *testing.T) {
	const tok = "sleutel-voor-de-test"
	t.Setenv(update.TokenEnv, tok)
	srv, ts, dir := newUpdateServer(t)
	srv.UpdateStarter = func(context.Context, string) error { return nil }

	before := store.Pipeline{ID: 1, Status: "running", CreatedAt: time.Now().Add(-time.Minute)}
	if on, _ := srv.UpdateGate(); on || srv.HoldPipeline(before) {
		t.Fatal("poort dicht zonder update")
	}
	time.Sleep(1100 * time.Millisecond) // RFC3339 heeft secondes
	if code, body := postUpdate(t, ts.URL, tok, `{"ref":"master"}`); code != http.StatusAccepted {
		t.Fatalf("POST: %d %s", code, body)
	}
	on, since := srv.UpdateGate()
	if !on {
		t.Fatal("geen update in afwachting")
	}
	// de pipeline die de update aanvroeg (ouder) loopt door: geen deadlock
	if srv.HoldPipeline(before) {
		t.Fatal("bestaande pipeline vastgehouden")
	}
	queued := store.Pipeline{ID: 2, Status: "queued", CreatedAt: since.Add(time.Second)}
	if !srv.HoldPipeline(queued) || srv.pipeStatusFor(queued) != "waiting_for_update" {
		t.Fatal("nieuwe pipeline niet vastgehouden")
	}
	if got := srv.pipeJSON(store.Repo{OwnerPath: "tim", Name: "x"}, queued)["status"]; got != "waiting_for_update" {
		t.Fatalf("API-status %v", got)
	}

	// tweede POST zonder force: 409; met force: vlag voor de updater
	if code, _ := postUpdate(t, ts.URL, tok, `{"ref":"master"}`); code != http.StatusConflict {
		t.Fatalf("dubbele update: %d", code)
	}
	if code, _ := postUpdate(t, ts.URL, tok, `{"ref":"master","force":true}`); code != http.StatusAccepted {
		t.Fatalf("force: %d", code)
	}
	req, _ := http.NewRequest(http.MethodGet, ts.URL+"/api/v1/admin/self-update", nil)
	req.Header.Set("Authorization", "Bearer "+tok)
	res, _ := http.DefaultClient.Do(req)
	var st map[string]any
	_ = json.NewDecoder(res.Body).Decode(&st)
	res.Body.Close()
	if st["force"] != true || st["status"] != "waiting" {
		t.Fatalf("status: %v", st)
	}

	// update klaar: poort open, wachtende pipelines starten
	_ = update.WriteStatus(dir, update.Status{Time: time.Now().UTC().Format(time.RFC3339), SHA: "x", Result: "ok"})
	if srv.HoldPipeline(queued) || srv.pipeStatusFor(queued) != "queued" {
		t.Fatal("poort bleef dicht na update")
	}
}

func TestUpdateGateSafetyValve(t *testing.T) {
	t.Setenv(update.TokenEnv, "x")
	srv, _, dir := newUpdateServer(t)
	srv.Cfg.CI.UpdateMaxWaitMin = 1
	old := time.Now().Add(-(time.Minute + updateRunning + time.Second))
	_ = update.WriteStatus(dir, update.Status{Time: old.UTC().Format(time.RFC3339), SHA: "x", Result: update.ResultWaiting})
	if on, _ := srv.UpdateGate(); on {
		t.Fatal("poort bleef dicht na de maximale wachttijd")
	}
	p := store.Pipeline{Status: "queued", CreatedAt: time.Now()}
	if srv.HoldPipeline(p) {
		t.Fatal("pipeline vastgehouden na time-out")
	}
}
