package server

import (
	"context"
	"path/filepath"
	"strconv"
	"strings"
	"testing"

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

func TestOpenAPISchemas(t *testing.T) {
	doc := openAPIDoc()
	schemas := doc["components"].(map[string]any)["schemas"].(map[string]any)
	for _, name := range []string{"Error", "MergeRequest", "Issue", "Pipeline", "Job", "Branch", "Webhook", "User", "UserUpdate"} {
		if _, ok := schemas[name]; !ok {
			t.Errorf("schema %s ontbreekt", name)
		}
	}
	props := schemas["MergeRequest"].(map[string]any)["properties"].(map[string]any)
	if _, ok := props["web_url"]; !ok {
		t.Fatal("MergeRequest mist web_url")
	}
	if _, ok := schemas["Issue"].(map[string]any)["properties"].(map[string]any)["web_url"]; !ok {
		t.Fatal("Issue mist web_url")
	}
	if _, ok := schemas["Pipeline"].(map[string]any)["properties"].(map[string]any)["web_url"]; !ok {
		t.Fatal("Pipeline mist web_url")
	}

	paths := doc["paths"].(map[string]any)
	assertBody(t, paths, "/projects/{owner}/{repo}/merge_requests", "post", "MergeRequestCreate")
	assertResp(t, paths, "/projects/{owner}/{repo}/merge_requests", "post", "201", "#/components/schemas/MergeRequest")
	assertItems(t, paths, "/projects/{owner}/{repo}/merge_requests", "get", "200", "#/components/schemas/MergeRequest")
	assertBody(t, paths, "/projects/{owner}/{repo}/merge_requests/{number}", "put", "MergeRequestUpdate")
	assertBody(t, paths, "/projects/{owner}/{repo}/merge_requests/{number}/merge", "post", "MergeRequestMerge")
	assertResp(t, paths, "/projects/{owner}/{repo}/merge_requests/{number}/merge", "post", "200", "#/components/schemas/MergeResult")

	if _, ok := paths["/repos/{owner}/{repo}/issues"]; !ok {
		t.Fatal("issues ontbreken in openapi")
	}
	assertBody(t, paths, "/repos/{owner}/{repo}/issues", "post", "IssueWrite")
	assertResp(t, paths, "/repos/{owner}/{repo}/issues", "post", "201", "#/components/schemas/Issue")
	assertResp(t, paths, "/repos/{owner}/{repo}/issues", "get", "200", "#/components/schemas/IssueList")
	assertBody(t, paths, "/repos/{owner}/{repo}/issues/{number}", "put", "IssueWrite")
	assertBody(t, paths, "/repos/{owner}/{repo}/issues/{number}/notes", "post", "IssueNoteCreate")

	assertBody(t, paths, "/projects/{owner}/{repo}/pipelines", "post", "PipelineCreate")
	assertResp(t, paths, "/projects/{owner}/{repo}/pipelines", "post", "201", "#/components/schemas/Pipeline")
	assertBody(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "PipelineRetry")
	assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "200", "#/components/schemas/Pipeline")
	assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "201", "#/components/schemas/Pipeline")
	assertItems(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs", "get", "200", "#/components/schemas/Job")
	assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs/{job}", "get", "200", "#/components/schemas/Job")

	assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches", "post", "BranchCreate")
	assertResp(t, paths, "/projects/{owner}/{repo}/repository/branches", "post", "201", "#/components/schemas/Branch")
	assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches/{branch}", "put", "BranchUpdate")
	assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches/{branch}", "delete", "BranchDelete")

	assertBody(t, paths, "/projects/{owner}/{repo}/webhooks", "post", "WebhookCreate")
	assertResp(t, paths, "/projects/{owner}/{repo}/webhooks", "post", "201", "#/components/schemas/Webhook")
	assertItems(t, paths, "/groups/{path}/webhooks", "get", "200", "#/components/schemas/Webhook")
	assertBody(t, paths, "/groups/{path}/webhooks", "post", "WebhookCreate")

	user := schemas["User"].(map[string]any)["properties"].(map[string]any)
	for _, key := range []string{"name", "bio", "web_url", "counts", "repos", "groups"} {
		if _, ok := user[key]; !ok {
			t.Errorf("User mist %s", key)
		}
	}
	assertBody(t, paths, "/user", "put", "UserUpdate")
	assertResp(t, paths, "/user", "get", "200", "#/components/schemas/User")
	assertResp(t, paths, "/users/{username}", "get", "200", "#/components/schemas/User")
	op := paths["/users/{username}"].(map[string]any)["get"].(map[string]any)
	sec, _ := op["security"].([]any)
	optional := false
	for _, item := range sec {
		req, _ := item.(map[string]any)
		if len(req) == 0 {
			optional = true
		}
	}
	if !optional {
		t.Fatal("GET /users/{username} moet zonder token mogen")
	}
}

func TestResourceWebURL(t *testing.T) {
	st, err := store.Open(filepath.Join(t.TempDir(), "bluegit.db"), bytes32())
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = st.Close() })
	ctx := context.Background()
	user, err := st.UpsertUser(ctx, 1, "timfa", "", false)
	if err != nil {
		t.Fatal(err)
	}
	repo, err := st.CreateRepo(ctx, "user", user.ID, "bluegit", "", "master", "public")
	if err != nil {
		t.Fatal(err)
	}
	mr, err := st.CreateMergeRequest(ctx, repo.ID, user.ID, "Titel", "", "topic", "master")
	if err != nil {
		t.Fatal(err)
	}
	iss, err := st.CreateIssue(ctx, repo.ID, user.ID, store.NewIssue{Title: "Bug"})
	if err != nil {
		t.Fatal(err)
	}
	pid, err := st.CreatePipeline(ctx, repo.ID, strings.Repeat("a", 40), "refs/heads/master", "push", "timfa", "titel", nil)
	if err != nil {
		t.Fatal(err)
	}
	pipe, err := st.PipelineByID(ctx, repo.ID, pid)
	if err != nil {
		t.Fatal(err)
	}

	srv := &Server{Cfg: config.Config{BaseURL: "https://git.timfalken.com/"}, Store: st}
	base := "https://git.timfalken.com/timfa/bluegit"
	if got := srv.mrJSON(repo, mr)["web_url"]; got != base+"/-/merge-requests/1" {
		t.Fatalf("mr web_url %v", got)
	}
	if got := srv.issueJSON(repo, iss, nil)["web_url"]; got != base+"/-/issues/1" {
		t.Fatalf("issue web_url %v", got)
	}
	wantPipe := base + "/-/pipelines/" + strconv.FormatInt(pid, 10)
	if got := srv.pipeJSON(repo, pipe)["web_url"]; got != wantPipe {
		t.Fatalf("pipeline web_url %v, wil %s", got, wantPipe)
	}
	srv.Cfg.BaseURL = ""
	if got := srv.mrJSON(repo, mr)["web_url"]; got != "/timfa/bluegit/-/merge-requests/1" {
		t.Fatalf("lege base mr web_url %v", got)
	}
}

func assertBody(t *testing.T, paths map[string]any, path, method, schema string) {
	t.Helper()
	op := operation(t, paths, path, method)
	ref := op["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)["$ref"]
	want := "#/components/schemas/" + schema
	if ref != want {
		t.Fatalf("%s %s body %v, wil %s", method, path, ref, want)
	}
}

func assertResp(t *testing.T, paths map[string]any, path, method, code, ref string) {
	t.Helper()
	schema := responseSchema(t, paths, path, method, code)
	if schema["$ref"] != ref {
		t.Fatalf("%s %s %s schema %v, wil %s", method, path, code, schema["$ref"], ref)
	}
}

func assertItems(t *testing.T, paths map[string]any, path, method, code, ref string) {
	t.Helper()
	schema := responseSchema(t, paths, path, method, code)
	items, _ := schema["items"].(map[string]any)
	if schema["type"] != "array" || items["$ref"] != ref {
		t.Fatalf("%s %s %s is geen array van %s: %v", method, path, code, ref, schema)
	}
}

func responseSchema(t *testing.T, paths map[string]any, path, method, code string) map[string]any {
	t.Helper()
	op := operation(t, paths, path, method)
	resp := op["responses"].(map[string]any)[code].(map[string]any)
	return resp["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)
}

func operation(t *testing.T, paths map[string]any, path, method string) map[string]any {
	t.Helper()
	item, ok := paths[path].(map[string]any)
	if !ok {
		t.Fatalf("pad ontbreekt: %s", path)
	}
	op, ok := item[method].(map[string]any)
	if !ok {
		t.Fatalf("operatie ontbreekt: %s %s", method, path)
	}
	return op
}
