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, "/projects/{owner}/{repo}/pipelines/{id}/retry", "POST"); op != nil {
		responses, _ := op["responses"].(map[string]any)
		if responses != nil {
			if okResp, ok := responses["200"]; ok {
				responses["201"] = okResp
			}
		}
	}
	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 + "/retry", method: "POST", code: "200", body: "PipelineRetry", 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"},
		{path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
		{path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
		{path: "/groups/{path}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
		{path: "/groups/{path}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
		{path: "/projects/{owner}/{repo}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
		{path: "/projects/{owner}/{repo}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
		{path: "/projects/{owner}/{repo}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
	}
}

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: queued, running, success, failed, canceled, waiting_for_update, waiting_for_job or manual. manual means only manual jobs are left, plus jobs that wait on them; such a pipeline is not running and has no finished_at until a manual job is played. A pipeline stopped by a newer pipeline stays canceled; see cancel_reason."),
			"display_status": str("Status as the UI shows it: obsolete when every canceled job was superseded by a newer pipeline on the same ref, otherwise equal to status. Only in list and get responses."),
			"cancel_reason":  str("For status canceled: superseded (a newer pipeline started for the same ref) or manual. Null otherwise. Only in list and get responses."),
			"waiting_for":    map[string]any{"type": "object", "nullable": true, "description": "For status waiting_for_job: the running doNotInterrupt job (job_id, job_name, pipeline_id) in an older pipeline on the same ref that this pipeline waits for. Only in list and get responses."},
			"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."),
		}),
		"PipelineRetry": obj("Retry a pipeline. all starts a new pipeline on the same commit, ref, source and merge request. failed requeues failed jobs and the skipped or never-started jobs that depend on them. The response is 201 for all and 200 for failed.", map[string]any{
			"mode": map[string]any{
				"type":        "string",
				"description": "all or failed.",
				"enum":        []any{"all", "failed"},
			},
		}),
		"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."),
			"display_status":   str("Status as the UI shows it: obsolete for a job canceled because a newer pipeline started for the same ref, otherwise equal to status."),
			"cancel_reason":    str("For status canceled: superseded or manual. Null otherwise."),
			"do_not_interrupt": boolean("doNotInterrupt is set: the job is never stopped automatically, and cancelling it while it runs needs force=true."),
			"failure_reason":   str("For status failed: job_execution_timeout, script_failure or runner_system_failure when known. Null otherwise."),
			"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: push, merge_request, pipeline_success, pipeline_failure, release_published, issue, issue_opened, issue_closed, issue_reopened, issue_updated, issue_comment, merge_request_comment. issue and merge_request also cover the finer issue_* and merge_request_comment events."),
			"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}, which is public. Without a token only public repositories and groups are included, and contributions count only those repositories. 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, see the list on the webhook schema."),
			"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("Name of the secret that holds the token. The value is never 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."),
		}),
		"WebhookUpdate": obj("Change a webhook. Omitted fields keep the stored value. An empty or omitted token keeps the stored secret reference; secret values are never returned.", map[string]any{
			"name":          str("Display name."),
			"preset":        str("Preset name."),
			"branch_filter": str("Branch filter."),
			"events":        strArr("Events, see the list on the webhook schema."),
			"active":        boolean("Enable or disable the hook."),
			"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("Name of the secret that holds the token. Empty keeps the current one."),
			"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. Empty keeps the current headers."),
			"body":          str("Body template."),
		}),
		"InheritedSecret": obj("A group secret the project inherits. Values are never returned. Jobs get group secrets first; a project secret with the same name wins.", map[string]any{
			"name":       str("Secret name."),
			"group":      str("Path of the group it comes from."),
			"protected":  boolean("Only injected on protected refs."),
			"overridden": boolean("A project secret with the same name replaces it."),
		}),
		"WebhookCopy": obj("Copy a webhook to a project or group where you are maintainer. Secrets the hook references and the target cannot already see are copied encrypted on the server; their values never reach the client.", map[string]any{
			"target_type": str("project or group."),
			"target":      str("Target path: owner/project or group path."),
			"name":        str("Optional new name. Default keeps the name."),
			"events":      strArr("Optional event filter. Default keeps the events."),
		}),
		"WebhookCopyResult": obj("The new webhook plus the names (never values) of copied secrets.", map[string]any{
			"id":              integer("New webhook id."),
			"name":            str("Display name."),
			"preset":          str("Preset name."),
			"url":             str("URL template."),
			"method":          str("HTTP method."),
			"events":          strArr("Events."),
			"branch_filter":   str("Branch filter."),
			"active":          boolean("Hook is enabled."),
			"scope":           str("repo or group."),
			"copied_secrets":  strArr("Names of secrets copied to the target."),
			"missing_secrets": strArr("Referenced secret names found nowhere; add them in the target."),
		}),
	}
}

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}
}
