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. " +
				"An issue event has object_kind issue and action opened, updated, closed, reopened or commented. " +
				"It includes the issue number, title, description, status, confidential flag, author, assignees, labels, milestone and due date. " +
				"A commented action also includes the comment text.",
		},
		"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."},
					},
				},
			},
			"/repos/{owner}/{repo}/issues": map[string]any{
				"get": map[string]any{
					"summary":     "List issues",
					"description": "Lists issues. Query state is open, closed or all. Query q searches title and description. Query label and assignee filter. Confidential issues of other people are omitted unless the token is Reporter or higher. A personal token is required. On a public repo any valid personal token can read. 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": "state", "in": "query", "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "q", "in": "query", "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "label", "in": "query", "schema": map[string]any{"type": "string"}},
						map[string]any{"name": "assignee", "in": "query", "schema": map[string]any{"type": "string"}},
					},
					"responses": map[string]any{
						"200": map[string]any{"description": "Issue list."},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot read this private repo."},
					},
				},
				"post": map[string]any{
					"summary":     "Create an issue",
					"description": "Creates an issue. Title is required. Readonly may set confidential. Labels, assignees, milestone and due_date need Reporter or higher. A label or milestone must already exist.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"responses": map[string]any{
						"201": map[string]any{"description": "Created issue."},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot create an issue, or it sent triage fields without Reporter."},
					},
				},
			},
			"/repos/{owner}/{repo}/issues/{number}": map[string]any{
				"get": map[string]any{
					"summary":     "Read an issue",
					"description": "Returns one issue and its comments. A confidential issue is 404 unless the token belongs to the author or a Reporter.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"responses": map[string]any{
						"200": map[string]any{"description": "The issue."},
						"401": map[string]any{"description": "Missing or invalid token."},
						"404": map[string]any{"description": "Unknown issue, or a confidential issue you cannot see."},
					},
				},
				"put": map[string]any{
					"summary":     "Update an issue",
					"description": "Omitted fields stay as they are. The author may change title, description and state. Labels, assignees, milestone, due_date and confidential need Reporter. State is open or closed.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"responses": map[string]any{
						"200": map[string]any{"description": "Updated issue."},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot change this field."},
					},
				},
			},
			"/repos/{owner}/{repo}/issues/{number}/notes": map[string]any{
				"post": map[string]any{
					"summary":     "Comment on an issue",
					"description": "Adds a comment. Readonly is enough. Sends an issue webhook with action commented.",
					"security":    []any{map[string]any{"bearer": []any{}}},
					"responses": map[string]any{
						"201": map[string]any{"description": "Created comment."},
						"401": map[string]any{"description": "Missing or invalid token."},
						"403": map[string]any{"description": "The token cannot comment."},
					},
				},
			},
			"/repos/{owner}/{repo}/labels": map[string]any{
				"get":  map[string]any{"summary": "List labels", "security": []any{map[string]any{"bearer": []any{}}}, "responses": map[string]any{"200": map[string]any{"description": "Labels."}}},
				"post": map[string]any{"summary": "Create or update a label", "description": "Maintainer only. Name uses letters, digits, spaces, hyphens or underscores. Color is # and six hex digits.", "security": []any{map[string]any{"bearer": []any{}}}, "responses": map[string]any{"201": map[string]any{"description": "Saved label."}, "403": map[string]any{"description": "Not a maintainer."}}},
			},
			"/repos/{owner}/{repo}/milestones": map[string]any{
				"get":  map[string]any{"summary": "List milestones", "security": []any{map[string]any{"bearer": []any{}}}, "responses": map[string]any{"200": map[string]any{"description": "Milestones."}}},
				"post": map[string]any{"summary": "Create or update a milestone", "description": "Maintainer only. due_on is YYYY-MM-DD or empty.", "security": []any{map[string]any{"bearer": []any{}}}, "responses": map[string]any{"201": map[string]any{"description": "Saved milestone."}, "403": map[string]any{"description": "Not a maintainer."}}},
			},
		},
		"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"),
			"issue":         post("Issue", "#/components/schemas/IssueEvent"),
		},
		"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."),
					"cancel_reason":  str("Only for status canceled: superseded (a newer pipeline started for the same ref; shown as Obsolete) or manual."),
					"failure_reason": str("Only for status failed, when known: job_execution_timeout, script_failure or runner_system_failure."),
					"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."),
					"event_name":    str("merge_request_comment for a comment, otherwise merge_request."),
					"note":          map[string]any{"$ref": "#/components/schemas/Note"},
				}, []string{"object_kind", "type", "event_name", "project", "merge_request"}),
				"Note": obj("A comment. Present only when action is commented.", map[string]any{
					"body":          str("Comment text."),
					"noteable_type": str("Issue or MergeRequest."),
					"noteable_id":   map[string]any{"type": "integer", "description": "Number of the issue or merge request."},
					"author":        str("User who wrote the comment."),
					"url":           str("Page of the issue or merge request."),
				}, []string{"body", "noteable_type", "noteable_id", "url"}),
				"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"}),
				"IssueEvent": obj("Opened, updated, closed, reopened or commented.", map[string]any{
					"object_kind": str("Always issue."),
					"type":        str("Always issue."),
					"project":     str("owner/name."),
					"actor":       str("User who did this action."),
					"summary":     str("One-line summary."),
					"url":         str("Issue page."),
					"issue":       map[string]any{"$ref": "#/components/schemas/Issue"},
					"comment":     str("Comment text. Present only when action is commented."),
					"event_name":  str("issue_opened, issue_closed, issue_reopened, issue_updated or issue_comment."),
					"note":        map[string]any{"$ref": "#/components/schemas/Note"},
				}, []string{"object_kind", "type", "event_name", "project", "issue"}),
				"Issue": obj("The issue this event is about.", map[string]any{
					"id":           map[string]any{"type": "integer", "description": "Number in the project."},
					"title":        str("Title."),
					"description":  str("Description. May be empty."),
					"status":       str("open or closed."),
					"confidential": boolean("True when the issue is confidential."),
					"author":       str("User who opened the issue."),
					"assignees":    map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
					"labels":       map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
					"milestone":    str("Milestone title, or empty."),
					"due_date":     str("Due date as YYYY-MM-DD, or empty."),
					"action":       str("opened, updated, closed, reopened or commented."),
					"url":          str("Issue page."),
				}, []string{"id", "title", "description", "status", "confidential", "author", "assignees", "labels", "milestone", "due_date", "action"}),
			},
		},
	}
	raw, err := json.MarshalIndent(doc, "", "  ")
	if err != nil {
		return []byte("{}\n")
	}
	return append(raw, '\n')
}
