package topdata

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"

	"gitea.westgate.pw/ShadowsOverWestgate/sow-tools/internal/project"
)

func TestDeployWikiDryRunDoesNotWriteRemoteOrManifest(t *testing.T) {
	root := t.TempDir()
	sourceDir := filepath.Join(root, "pages")
	if err := os.MkdirAll(filepath.Join(sourceDir, "skills"), 0755); err != nil {
		t.Fatalf("create source dir: %v", err)
	}
	if err := os.WriteFile(filepath.Join(sourceDir, "skills", "athletics.txt"), []byte("Generated athletics page\n"), 0644); err != nil {
		t.Fatalf("write source page: %v", err)
	}

	putPageCalls := 0
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Method string `json:"method"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			t.Fatalf("decode rpc request: %v", err)
		}

		var result any
		switch req.Method {
		case "wiki.getPage":
			result = "Existing athletics page\n"
		case "dokuwiki.getPagelist":
			result = []any{}
		case "wiki.putPage":
			putPageCalls++
			result = true
		default:
			t.Fatalf("unexpected rpc method %q", req.Method)
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(map[string]any{
			"jsonrpc": "2.0",
			"id":      1,
			"result":  result,
		}); err != nil {
			t.Fatalf("encode rpc response: %v", err)
		}
	}))
	defer server.Close()

	manifestPath := filepath.Join(root, "deploy-manifest.json")
	result, err := DeployWikiWithOptions(&project.Project{}, DeployWikiOptions{
		SourceDir:    sourceDir,
		Endpoint:     server.URL,
		Username:     "wiki-user",
		Password:     "wiki-pass",
		ManifestPath: manifestPath,
		DryRun:       true,
	}, nil)
	if err != nil {
		t.Fatalf("DeployWikiWithOptions dry run failed: %v", err)
	}

	if result.Updated != 1 {
		t.Fatalf("expected one planned update, got %d", result.Updated)
	}
	if putPageCalls != 0 {
		t.Fatalf("expected dry run not to call wiki.putPage, got %d calls", putPageCalls)
	}
	if _, err := os.Stat(manifestPath); !os.IsNotExist(err) {
		t.Fatalf("expected dry run not to write manifest, got %v", err)
	}
}
