package server

import "strings"

// decorateAPI vult request- en response-schema's in voor de kernobjecten.
func decorateAPI(paths map[string]map[string]any, schemas map[string]any) {
	for name, schema := range apiSchemas() {
		schemas[name] = schema
	}
	for _, b := range apiBinds() {
		op := apiOp(paths, b.path, b.method)
		if op == nil {
			continue
		}
		if b.body != "" {
			op["requestBody"] = map[string]any{
				"required": true,
				"content":  jsonSchema(schemaRef(b.body)),
			}
		}
		responses, _ := op["responses"].(map[string]any)
		if responses == nil {
			responses = map[string]any{}
			op["responses"] = responses
		}
		if b.empty {
			responses[b.code] = map[string]any{"description": "No content"}
			delete(responses, "200")
			continue
		}
		schema := schemaRef(b.resp)
		if b.array {
			schema = map[string]any{"type": "array", "items": schema}
		}
		responses[b.code] = map[string]any{
			"description": "OK",
			"content":     jsonSchema(schema),
		}
	}
	if op := apiOp(paths, "/repos/{owner}/{repo}/issues/{number}/notes", "POST"); op != nil {
		responses, _ := op["responses"].(map[string]any)
		if responses == nil {
			return
		}
		responses["200"] = map[string]any{
			"description": "Issue, when the note contains only quick actions.",
			"content":     jsonSchema(schemaRef("Issue")),
		}
	}
}

func apiOp(paths map[string]map[string]any, path, method string) map[string]any {
	item := paths[path]
	if item == nil {
		return nil
	}
	op, _ := item[strings.ToLower(method)].(map[string]any)
	return op
}

func schemaRef(name string) map[string]any {
	return map[string]any{"$ref": "#/components/schemas/" + name}
}

func jsonSchema(schema map[string]any) map[string]any {
	return map[string]any{"application/json": map[string]any{"schema": schema}}
}

type apiBind struct {
	path, method, body, resp, code string
	array, empty                   bool
}

func apiBinds() []apiBind {
	const (
		mrs      = "/projects/{owner}/{repo}/merge_requests"
		mr       = mrs + "/{number}"
		pipes    = "/projects/{owner}/{repo}/pipelines"
		pipe     = pipes + "/{id}"
		job      = pipe + "/jobs/{job}"
		issues   = "/repos/{owner}/{repo}/issues"
		issue    = issues + "/{number}"
		branches = "/projects/{owner}/{repo}/repository/branches"
		branch   = branches + "/{branch}"
	)
	return []apiBind{
		{path: "/user", method: "GET", code: "200", resp: "User"},
		{path: "/user", method: "PUT", code: "200", body: "UserUpdate", resp: "User"},
		{path: "/users/{username}", method: "GET", code: "200", resp: "User"},

		{path: mrs, method: "GET", code: "200", resp: "MergeRequest", array: true},
		{path: mrs, method: "POST", code: "201", body: "MergeRequestCreate", resp: "MergeRequest"},
		{path: mr, method: "GET", code: "200", resp: "MergeRequest"},
		{path: mr, method: "PUT", code: "200", body: "MergeRequestUpdate", resp: "MergeRequest"},
		{path: mr + "/merge", method: "POST", code: "200", body: "MergeRequestMerge", resp: "MergeResult"},
		{path: mr + "/close", method: "POST", code: "200", resp: "MergeState"},
		{path: mr + "/reopen", method: "POST", code: "200", resp: "MergeState"},

		{path: issues, method: "GET", code: "200", resp: "IssueList"},
		{path: issues, method: "POST", code: "201", body: "IssueWrite", resp: "Issue"},
		{path: issue, method: "GET", code: "200", resp: "Issue"},
		{path: issue, method: "PUT", code: "200", body: "IssueWrite", resp: "Issue"},
		{path: issue, method: "DELETE", code: "204", empty: true},
		{path: issue + "/notes", method: "POST", code: "201", body: "IssueNoteCreate", resp: "IssueNote"},

		{path: pipes, method: "GET", code: "200", resp: "Pipeline", array: true},
		{path: pipes, method: "POST", code: "201", body: "PipelineCreate", resp: "Pipeline"},
		{path: pipe, method: "GET", code: "200", resp: "Pipeline"},
		{path: pipe + "/cancel", method: "POST", code: "200", resp: "Pipeline"},
		{path: pipe + "/jobs", method: "GET", code: "200", resp: "Job", array: true},
		{path: job, method: "GET", code: "200", resp: "Job"},
		{path: job + "/play", method: "POST", code: "200", resp: "Job"},
		{path: job + "/retry", method: "POST", code: "200", resp: "Job"},
		{path: job + "/cancel", method: "POST", code: "200", resp: "Job"},

		{path: branches, method: "GET", code: "200", resp: "Branch", array: true},
		{path: branches, method: "POST", code: "201", body: "BranchCreate", resp: "Branch"},
		{path: branch, method: "PUT", code: "200", body: "BranchUpdate", resp: "Branch"},
		{path: branch, method: "DELETE", code: "204", body: "BranchDelete", empty: true},

		{path: "/groups/{path}/webhooks", method: "GET", code: "200", resp: "Webhook", array: true},
		{path: "/groups/{path}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
		{path: "/projects/{owner}/{repo}/webhooks", method: "GET", code: "200", resp: "Webhook", array: true},
		{path: "/projects/{owner}/{repo}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
	}
}

func apiSchemas() map[string]any {
	when := str("RFC3339 timestamp. Null when the moment has not happened yet.")
	return map[string]any{
		"MergeRequest": obj("Merge request.", map[string]any{
			"id":                    integer("Internal id."),
			"iid":                   integer("Merge request number in the project."),
			"title":                 str("Title."),
			"description":           str("Description."),
			"source_branch":         str("Source branch."),
			"target_branch":         str("Target branch."),
			"author":                str("Author username."),
			"state":                 str("open, closed or merged."),
			"draft":                 boolean("Draft merge request."),
			"labels":                str("Comma-separated label names."),
			"remove_source_branch":  boolean("Delete the source branch after a successful merge."),
			"squash":                boolean("Squash commits when merging."),
			"squash_commit_message": str("Commit message used when squash is enabled. Empty uses the title."),
			"web_url":               str("Full page URL. An empty base URL yields a path."),
			"created_at":            when,
			"updated_at":            when,
		}),
		"MergeRequestCreate": obj("Fields for a new merge request. Omitted remove_source_branch means true. Omitted squash means false.", map[string]any{
			"title":                 str("Title."),
			"description":           str("Description."),
			"source_branch":         str("Source branch."),
			"target_branch":         str("Target branch."),
			"draft":                 boolean("Create as draft."),
			"remove_source_branch":  boolean("Delete the source branch after merge. Omitted means true."),
			"squash":                boolean("Squash commits. Omitted means false."),
			"squash_commit_message": str("Squash commit message. Empty uses the merge request title."),
		}),
		"MergeRequestUpdate": obj("Fields to change on a merge request. Omitted merge options keep the stored value.", map[string]any{
			"title":                 str("Title."),
			"description":           str("Description."),
			"labels":                str("Comma-separated label names."),
			"remove_source_branch":  boolean("Delete the source branch after merge."),
			"squash":                boolean("Squash commits."),
			"squash_commit_message": str("Squash commit message."),
		}),
		"MergeRequestMerge": obj("Merge options for this attempt. Omitted fields keep the stored value.", map[string]any{
			"remove_source_branch":  boolean("Delete the source branch after merge."),
			"squash":                boolean("Squash commits."),
			"squash_commit_message": str("Squash commit message."),
		}),
		"MergeResult": obj("Result of a merge.", map[string]any{
			"state":                 str("merged."),
			"source_branch_removed": boolean("True when the source branch was deleted."),
			"source_branch_skip":    str("Empty when the branch was removed. Otherwise disabled, protected, default, forbidden, missing or error."),
			"web_url":               str("Full page URL of the merge request."),
		}),
		"MergeState": obj("State after close or reopen.", map[string]any{
			"state":   str("open or closed."),
			"web_url": str("Full page URL of the merge request."),
		}),
		"Issue": obj("Issue. The list omits notes.", map[string]any{
			"id":           integer("Issue number in the project."),
			"title":        str("Title."),
			"description":  str("Description."),
			"status":       str("open or closed."),
			"confidential": boolean("Hidden from users who cannot triage."),
			"author":       str("Author username."),
			"assignees":    strArr("Assignee usernames."),
			"labels":       strArr("Label names."),
			"milestone":    str("Milestone title."),
			"due_date":     str("Due date, YYYY-MM-DD, or empty."),
			"created_at":   when,
			"updated_at":   when,
			"closed_at":    when,
			"web_url":      str("Full page URL. An empty base URL yields a path."),
			"notes":        map[string]any{"type": "array", "items": schemaRef("IssueNote"), "description": "Notes. Omitted on the list."},
		}),
		"IssueNote": obj("Issue note.", map[string]any{
			"id":         integer("Note id."),
			"author":     str("Author username."),
			"body":       str("Note text."),
			"created_at": when,
		}),
		"IssueList": obj("Issue list.", map[string]any{
			"issues": map[string]any{"type": "array", "items": schemaRef("Issue")},
		}),
		"IssueWrite": obj("Fields to create or update an issue. Omitted fields stay unchanged on update.", map[string]any{
			"title":        str("Title. Required when creating."),
			"description":  str("Description."),
			"state":        str("open or closed."),
			"confidential": boolean("Confidential issue."),
			"labels":       strArr("Label names."),
			"assignees":    strArr("Assignee usernames."),
			"milestone":    str("Milestone title."),
			"due_date":     str("Due date, YYYY-MM-DD, or empty."),
		}),
		"IssueNoteCreate": obj("New issue note. A body that is only quick actions returns the issue instead of a note.", map[string]any{
			"body": str("Note text, including optional quick actions."),
		}),
		"Pipeline": obj("Pipeline.", map[string]any{
			"id":          integer("Pipeline id."),
			"sha":         str("Commit SHA."),
			"ref":         str("Git ref, for example refs/heads/master."),
			"status":      str("Pipeline status."),
			"source":      str("Trigger source."),
			"actor":       str("Username that started the pipeline."),
			"created_at":  when,
			"started_at":  when,
			"finished_at": when,
			"web_url":     str("Full page URL. An empty base URL yields a path."),
		}),
		"PipelineCreate": obj("Start a pipeline.", map[string]any{
			"ref": str("Branch, tag or full ref to run."),
		}),
		"Job": obj("CI job.", map[string]any{
			"id":            integer("Job id."),
			"name":          str("Job name."),
			"stage":         str("Stage name."),
			"status":        str("Job status."),
			"when":          str("When the job runs."),
			"allow_failure": boolean("A failed job does not fail the pipeline."),
			"started_at":    when,
			"finished_at":   when,
		}),
		"Branch": obj("Branch tip. Create and rename responses only include name.", map[string]any{
			"name":    str("Branch name."),
			"commit":  str("Tip commit SHA."),
			"subject": str("Tip commit subject."),
			"date":    str("Tip commit date."),
			"default": boolean("True for the default branch."),
		}),
		"BranchCreate": obj("Create a branch.", map[string]any{
			"name": str("New branch name."),
			"from": str("Existing branch or commit to start from."),
		}),
		"BranchUpdate": obj("Rename a branch.", map[string]any{
			"name":    str("New branch name."),
			"confirm": str("Current branch name, repeated as confirmation."),
		}),
		"BranchDelete": obj("Delete a branch.", map[string]any{
			"confirm": str("Branch name, repeated as confirmation."),
		}),
		"Webhook": obj("Webhook.", map[string]any{
			"id":            integer("Webhook id."),
			"name":          str("Display name."),
			"preset":        str("Preset name, or empty for a custom hook."),
			"url":           str("URL template."),
			"method":        str("HTTP method."),
			"events":        strArr("Events that trigger the hook."),
			"branch_filter": str("Branch filter. Empty matches every branch."),
			"active":        boolean("Hook is enabled."),
		}),
		"User": obj("User. counts, repos and groups are present on GET /users/{username}. instance_admin and language are present for the signed-in user.", map[string]any{
			"id":             integer("User id."),
			"username":       str("Username."),
			"name":           str("Display name. Empty when unset."),
			"bio":            str("Profile text. Empty when unset."),
			"avatar_url":     str("Avatar URL."),
			"created_at":     when,
			"web_url":        str("Profile page at /users/{username}."),
			"instance_admin": boolean("Instance administrator. Only on the signed-in user."),
			"language":       str("Interface language. Only on the signed-in user."),
			"counts": obj("Totals the viewer is allowed to see.", map[string]any{
				"repos":         integer("Owned repositories visible to the viewer."),
				"groups":        integer("Groups the user belongs to that the viewer may see."),
				"contributions": integer("Contributions in the last 12 months in repositories the viewer may see."),
			}),
			"repos":  map[string]any{"type": "array", "description": "Owned repositories visible to the viewer.", "items": schemaRef("UserRepo")},
			"groups": map[string]any{"type": "array", "description": "Groups visible to the viewer.", "items": schemaRef("UserGroup")},
		}),
		"UserUpdate": obj("Fields to change on the signed-in user. Omitted fields stay unchanged.", map[string]any{
			"name":     str("Display name. Empty clears it."),
			"bio":      str("Profile text. Empty clears it. Newlines are kept."),
			"language": str("Interface language."),
		}),
		"UserRepo": obj("Repository on a user profile.", map[string]any{
			"id":          integer("Repository id."),
			"name":        str("Repository name."),
			"path":        str("Full path, owner/name."),
			"description": str("Description."),
			"visibility":  str("public or private."),
			"web_url":     str("Full page URL."),
		}),
		"UserGroup": obj("Group on a user profile.", map[string]any{
			"id":          integer("Group id."),
			"name":        str("Group name."),
			"path":        str("Group path."),
			"description": str("Description."),
			"visibility":  str("public or private."),
			"web_url":     str("Full page URL."),
		}),
		"WebhookCreate": obj("Create a webhook. Preset fields depend on the chosen preset.", map[string]any{
			"name":          str("Display name."),
			"preset":        str("Preset name."),
			"branch_filter": str("Branch filter."),
			"events":        strArr("Events."),
			"url":           str("URL template."),
			"username":      str("Username for the preset."),
			"avatar":        str("Avatar URL."),
			"icon":          str("Icon URL or emoji."),
			"alias":         str("Alias."),
			"token":         str("Token. Stored as a secret and not returned."),
			"chat":          str("Chat id."),
			"server":        str("Server URL."),
			"topic":         str("Topic."),
			"homeserver":    str("Matrix homeserver."),
			"room":          str("Matrix room."),
			"method":        str("HTTP method."),
			"content_type":  str("Content type."),
			"headers":       str("Extra headers."),
			"body":          str("Body template."),
		}),
	}
}

func obj(desc string, props map[string]any) map[string]any {
	return map[string]any{"type": "object", "description": desc, "properties": props}
}

func str(desc string) map[string]any {
	return map[string]any{"type": "string", "description": desc}
}

func strArr(desc string) map[string]any {
	return map[string]any{"type": "array", "description": desc, "items": map[string]any{"type": "string"}}
}

func boolean(desc string) map[string]any {
	return map[string]any{"type": "boolean", "description": desc}
}

func integer(desc string) map[string]any {
	return map[string]any{"type": "integer", "format": "int64", "description": desc}
}
