package docs

import (
	"encoding/json"
	"net/http"
	"testing"

	"gitea.parodia.dev/drwily/petal/internal/db"
)

// newDoc creates a document and returns its id.
func newDoc(t *testing.T, srv http.Handler) string {
	t.Helper()
	rec := do(t, srv, http.MethodPost, "/", "")
	if rec.Code != http.StatusCreated {
		t.Fatalf("create doc: code=%d body=%s", rec.Code, rec.Body)
	}
	var d db.Document
	if err := json.Unmarshal(rec.Body.Bytes(), &d); err != nil {
		t.Fatalf("decode doc: %v", err)
	}
	return d.ID
}

func listVersions(t *testing.T, srv http.Handler, id string) []db.DocumentVersion {
	t.Helper()
	rec := do(t, srv, http.MethodGet, "/"+id+"/versions", "")
	if rec.Code != http.StatusOK {
		t.Fatalf("list versions: code=%d body=%s", rec.Code, rec.Body)
	}
	var vs []db.DocumentVersion
	if err := json.Unmarshal(rec.Body.Bytes(), &vs); err != nil {
		t.Fatalf("decode versions: %v", err)
	}
	return vs
}

func TestVersionLifecycle(t *testing.T) {
	srv := newTestServer(t)
	id := newDoc(t, srv)

	// A bare rename (no content) must not snapshot.
	do(t, srv, http.MethodPut, "/"+id, `{"title":"Just A Name"}`)
	if vs := listVersions(t, srv, id); len(vs) != 0 {
		t.Fatalf("rename should not snapshot, got %d", len(vs))
	}

	// First real body save takes one auto snapshot (no prior version to throttle).
	body := `{"content":"{\"type\":\"doc\"}","content_text":"first draft","word_count":2}`
	do(t, srv, http.MethodPut, "/"+id, body)
	vs := listVersions(t, srv, id)
	if len(vs) != 1 || vs[0].Kind != db.VersionKindAuto {
		t.Fatalf("expected 1 auto version, got %+v", vs)
	}
	// List view omits heavy content fields.
	if vs[0].Content != "" {
		t.Fatalf("list should omit content, got %q", vs[0].Content)
	}

	// A near-immediate second save is throttled (no new auto version).
	do(t, srv, http.MethodPut, "/"+id, `{"content":"{\"type\":\"doc\"}","content_text":"first draft v2","word_count":3}`)
	if vs := listVersions(t, srv, id); len(vs) != 1 {
		t.Fatalf("second save within interval should be throttled, got %d", len(vs))
	}

	// Manual snapshot always records, capturing current saved state.
	rec := do(t, srv, http.MethodPost, "/"+id+"/versions", "")
	if rec.Code != http.StatusCreated {
		t.Fatalf("manual snapshot: code=%d body=%s", rec.Code, rec.Body)
	}
	var manual db.DocumentVersion
	_ = json.Unmarshal(rec.Body.Bytes(), &manual)
	if manual.Kind != db.VersionKindManual {
		t.Fatalf("expected manual kind, got %q", manual.Kind)
	}

	// Mutate the live doc, then restore the manual snapshot.
	do(t, srv, http.MethodPut, "/"+id, `{"content":"{\"type\":\"doc\"}","content_text":"ruined everything","word_count":2}`)
	rec = do(t, srv, http.MethodPost, "/"+id+"/versions/"+manual.ID+"/restore", "")
	if rec.Code != http.StatusOK {
		t.Fatalf("restore: code=%d body=%s", rec.Code, rec.Body)
	}
	var restored db.Document
	_ = json.Unmarshal(rec.Body.Bytes(), &restored)
	if restored.ContentText != "first draft v2" {
		t.Fatalf("restore did not bring back snapshot text: %q", restored.ContentText)
	}

	// Restore left a pre_restore safety copy, so the bad state is itself recoverable.
	var foundPreRestore bool
	for _, v := range listVersions(t, srv, id) {
		if v.Kind == db.VersionKindPreRestore {
			foundPreRestore = true
		}
	}
	if !foundPreRestore {
		t.Fatal("restore should record a pre_restore safety snapshot")
	}
}

func TestVersionNotFound(t *testing.T) {
	srv := newTestServer(t)
	id := newDoc(t, srv)
	if rec := do(t, srv, http.MethodGet, "/"+id+"/versions/nope", ""); rec.Code != http.StatusNotFound {
		t.Fatalf("expected 404 for unknown version, got %d", rec.Code)
	}
}
