package webhook

import "encoding/json"

// OpenAPI beschrijft de JSON-body die een webhook ontvangt.
func OpenAPI() []byte {
	obj := func(desc string, props map[string]any, required []string) map[string]any {
		return map[string]any{
			"type": "object", "description": desc,
			"properties": props, "required": required,
		}
	}
	str := func(desc string) map[string]any {
		return map[string]any{"type": "string", "description": desc}
	}
	num := func(desc string) map[string]any {
		return map[string]any{"type": "number", "description": desc}
	}
	boolean := func(desc string) map[string]any {
		return map[string]any{"type": "boolean", "description": desc}
	}
	post := func(summary, ref string) map[string]any {
		return map[string]any{
			"post": map[string]any{
				"summary": summary,
				"requestBody": map[string]any{
					"required": true,
					"content": map[string]any{
						"application/json": map[string]any{
							"schema": map[string]any{"$ref": ref},
						},
					},
				},
				"responses": map[string]any{"200": map[string]any{"description": "The receiver accepted the event."}},
			},
		}
	}
	doc := map[string]any{
		"openapi": "3.1.0",
		"info": map[string]any{
			"title":   "BlueGit webhook payloads",
			"version": "1",
			"description": "JSON body of a BlueGit webhook when the body template is empty. " +
				"pipeline_success and pipeline_failure include the pipeline and every job. " +
				"Every job includes its console output: the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. " +
				"log_truncated is true when the log was cut. log_url is then GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log and needs Authorization Bearer with a personal token that can read the repo. " +
				"A push lists ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload does not include the diff text. " +
				"diff_url for a commit is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. " +
				"A merge request includes reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. " +
				"diff_url for a merge request is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. " +
				"Both diff requests need Authorization Bearer and a personal token that can read the repo. " +
				"A merge request uses action opened, merged or commented, and commented includes the comment text. " +
				"A release lists the tag, name, commit and asset URLs.",
		},
		"servers": []any{map[string]any{"url": "/api/v1"}},
		"paths": map[string]any{
			"/repos/{owner}/{repo}/commits/{sha}/diff": map[string]any{
				"get": map[string]any{
					"summary":     "Commit diff",
					"description": "Returns the unified diff of the commit against its first parent as text/plain. A root commit is compared with an empty tree. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"parameters": []any{
						map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "sha", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
					},
					"responses": map[string]any{
						"200": map[string]any{
							"description": "Unified diff.",
							"content":     map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
						},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot read this private repo."},
						"404": map[string]any{"description": "Unknown repo or commit."},
					},
				},
			},
			"/repos/{owner}/{repo}/merge-requests/{id}/diff": map[string]any{
				"get": map[string]any{
					"summary":     "Merge request diff",
					"description": "Returns the three-dot unified diff from the target branch to the source branch as text/plain. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"parameters": []any{
						map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
					},
					"responses": map[string]any{
						"200": map[string]any{
							"description": "Unified diff.",
							"content":     map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
						},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot read this private repo."},
						"404": map[string]any{"description": "Unknown repo or merge request."},
					},
				},
			},
			"/repos/{owner}/{repo}/jobs/{id}/log": map[string]any{
				"get": map[string]any{
					"summary":     "Full job log",
					"description": "Returns the full console output as text/plain. Secret values of at least 8 characters are replaced with [MASKED]. Requires a personal access token. A token that can read the repo is enough, and on a public repo any valid personal token is enough. Job tokens are rejected.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"parameters": []any{
						map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
					},
					"responses": map[string]any{
						"200": map[string]any{
							"description": "Full log.",
							"content":     map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
						},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot read this private repo."},
						"404": map[string]any{"description": "Unknown repo or job."},
					},
				},
			},
		},
		"webhooks": map[string]any{
			"pipeline":      post("Pipeline finished", "#/components/schemas/PipelineEvent"),
			"push":          post("Push", "#/components/schemas/PushEvent"),
			"merge_request": post("Merge request", "#/components/schemas/MergeRequestEvent"),
			"release":       post("Release published", "#/components/schemas/ReleaseEvent"),
		},
		"components": map[string]any{
			"securitySchemes": map[string]any{
				"bearer": map[string]any{"type": "http", "scheme": "bearer", "description": "Personal access token (bg_)."},
			},
			"schemas": map[string]any{
				"PipelineEvent": obj("pipeline_success or pipeline_failure.", map[string]any{
					"object_kind": str("Always pipeline."),
					"type":        str("pipeline_success or pipeline_failure."),
					"project":     str("owner/name."),
					"actor":       str("User who started the pipeline."),
					"summary":     str("One-line summary."),
					"url":         str("Pipeline page."),
					"pipeline_id": str("Same id as pipeline.id, as text."),
					"pipeline":    map[string]any{"$ref": "#/components/schemas/Pipeline"},
					"jobs":        map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Job"}},
				}, []string{"object_kind", "type", "project", "pipeline", "jobs"}),
				"Pipeline": obj("The pipeline this event is about.", map[string]any{
					"id":             map[string]any{"type": "integer", "description": "Pipeline id."},
					"status":         str("success or failed."),
					"ref":            str("Full ref, such as refs/heads/master."),
					"sha":            str("Commit SHA."),
					"commit_message": str("Subject and body of the commit."),
					"author":         str("User who started the pipeline."),
					"duration":       num("Seconds from start to finish."),
					"url":            str("Pipeline page."),
				}, []string{"id", "status", "ref", "sha", "commit_message", "author", "duration"}),
				"Job": obj("One job. log is always the console tail. log_url is present only when log_truncated is true.", map[string]any{
					"name":          str("Job name."),
					"stage":         str("Stage name."),
					"status":        str("Job status."),
					"duration":      num("Seconds the job ran."),
					"allow_failure": boolean("True when a failure does not fail the pipeline."),
					"web_url":       str("Job page."),
					"log":           str("Last 200 lines of the console output, at most 64 KiB. Secrets of at least 8 characters are [MASKED]."),
					"log_truncated": boolean("True when log is shorter than the stored console output."),
					"log_url":       str("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Present only when log_truncated is true. Requires Authorization Bearer and a personal token that can read the repo. The response is the full log as text/plain, with secrets masked."),
				}, []string{"name", "stage", "status", "duration", "allow_failure", "web_url", "log", "log_truncated"}),
				"PushEvent": obj("A branch or tag update.", map[string]any{
					"object_kind": str("Always push."),
					"type":        str("Always push."),
					"project":     str("owner/name."),
					"actor":       str("User who pushed."),
					"ref":         str("Full ref."),
					"before":      str("Previous SHA, or 40 zeros when the ref is new."),
					"after":       str("New SHA."),
					"commits":     map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
				}, []string{"object_kind", "type", "project", "ref", "before", "after", "commits"}),
				"Commit": obj("One commit. The diff text is not included.", map[string]any{
					"sha":       str("Commit SHA."),
					"message":   str("Subject and body."),
					"author":    str("Name and email."),
					"timestamp": str("Author time in RFC3339."),
					"url":       str("Commit page."),
					"files":     map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
					"diff_url":  str("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the unified diff as text/plain."),
				}, []string{"sha", "message", "author", "timestamp", "url", "files", "diff_url"}),
				"FileChange": obj("One changed file, without the diff text.", map[string]any{
					"path":          str("Path after the change."),
					"status":        str("added, modified, removed or renamed."),
					"previous_path": str("Path before a rename."),
					"additions":     map[string]any{"type": "integer", "description": "Added lines. Zero for a binary file."},
					"deletions":     map[string]any{"type": "integer", "description": "Deleted lines. Zero for a binary file."},
					"binary":        boolean("True when the file is binary."),
				}, []string{"path", "status", "additions", "deletions"}),
				"MergeRequestEvent": obj("Opened, merged or commented.", map[string]any{
					"object_kind":   str("Always merge_request."),
					"type":          str("Always merge_request."),
					"project":       str("owner/name."),
					"actor":         str("User who did this action."),
					"merge_request": map[string]any{"$ref": "#/components/schemas/MergeRequest"},
					"comment":       str("Comment text. Present only when action is commented."),
				}, []string{"object_kind", "type", "project", "merge_request"}),
				"MergeRequest": obj("The merge request.", map[string]any{
					"id":            map[string]any{"type": "integer", "description": "Number in the project."},
					"title":         str("Title."),
					"description":   str("Description. May be empty."),
					"source_branch": str("Source branch."),
					"target_branch": str("Target branch."),
					"status":        str("open, merged or closed."),
					"author":        str("User who opened the merge request."),
					"action":        str("opened, merged or commented."),
					"url":           str("Merge request page."),
					"reviewers":     map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Reviewer"}},
					"comments":      map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Comment"}},
					"commits":       map[string]any{"type": "array", "description": "Up to 20 commits on the source branch that the target does not have, oldest first.", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
					"diff_stats":    map[string]any{"$ref": "#/components/schemas/DiffStats"},
					"diff_url":      str("GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the three-dot unified diff as text/plain."),
				}, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action", "reviewers", "comments", "commits", "diff_stats", "diff_url"}),
				"Reviewer": obj("The current review of one person.", map[string]any{
					"username": str("Username."),
					"status":   str("approved, changes, rejected or dismissed."),
				}, []string{"username", "status"}),
				"Comment": obj("One comment on the merge request.", map[string]any{
					"id":         map[string]any{"type": "integer", "description": "Comment id."},
					"author":     str("Username."),
					"body":       str("Comment text."),
					"created_at": str("Time in RFC3339."),
					"file_path":  str("File, when the comment is on a line."),
					"line_start": map[string]any{"type": "integer", "description": "First line."},
					"line_end":   map[string]any{"type": "integer", "description": "Last line."},
					"parent_id":  map[string]any{"type": "integer", "description": "Parent comment, when this is a reply."},
				}, []string{"id", "author", "body", "created_at"}),
				"DiffStats": obj("Line counts of the merge request diff. The diff text is not included.", map[string]any{
					"additions": map[string]any{"type": "integer", "description": "Added lines."},
					"deletions": map[string]any{"type": "integer", "description": "Deleted lines."},
					"files":     map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
				}, []string{"additions", "deletions", "files"}),
				"ReleaseEvent": obj("A published release.", map[string]any{
					"object_kind": str("Always release."),
					"type":        str("Always release_published."),
					"project":     str("owner/name."),
					"release_tag": str("Same value as release.tag."),
					"release":     map[string]any{"$ref": "#/components/schemas/Release"},
				}, []string{"object_kind", "type", "project", "release"}),
				"Release": obj("The release.", map[string]any{
					"tag":    str("Tag name."),
					"name":   str("Release title."),
					"commit": str("Commit SHA."),
					"assets": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Asset"}},
				}, []string{"tag", "name", "commit", "assets"}),
				"Asset": obj("A file attached to the release.", map[string]any{
					"name": str("File name."),
					"url":  str("Download URL."),
					"size": map[string]any{"type": "integer", "description": "Size in bytes."},
				}, []string{"name", "url", "size"}),
			},
		},
	}
	raw, err := json.MarshalIndent(doc, "", "  ")
	if err != nil {
		return []byte("{}\n")
	}
	return append(raw, '\n')
}
