/*
 * Copyright Nico Sonack <nsonack@herrhotzenplotz.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <gcli/gitea/pulls.h>
#include <gcli/gitea/repos.h>
#include <gcli/gitea/issues.h>
#include <gcli/github/issues.h>
#include <gcli/github/pulls.h>

#include <gcli/port/err.h>
#include <gcli/port/string.h>

#include <gcli/json_gen.h>
#include <gcli/url.h>

#include <templates/github/pulls.h>

#include <stdarg.h>

int
gitea_pull_make_url(struct gcli_ctx *ctx, struct gcli_path const *const path,
                    char **url, char const *const suffix_fmt, ...)
{
	char *suffix = NULL;
	int rc = 0;
	va_list vp;

	va_start(vp, suffix_fmt);
	suffix = gcli_vasprintf(suffix_fmt, vp);
	va_end(vp);

	switch (path->kind) {
	case GCLI_PATH_DEFAULT: {
		char *e_owner = NULL, *e_repo = NULL;

		e_owner = gcli_urlencode(path->as_default.owner);
		e_repo  = gcli_urlencode(path->as_default.repo);

		*url = gcli_asprintf("%s/repos/%s/%s/pulls/%"PRIid"%s",
		                     gcli_get_apibase(ctx), e_owner, e_repo,
		                     path->as_default.id, suffix);

		gcli_clear_ptr(&e_owner);
		gcli_clear_ptr(&e_repo);
	} break;
	case GCLI_PATH_URL: {
		*url = gcli_asprintf("%s%s", path->as_url, suffix);
	} break;
	default: {
		rc = gcli_error(ctx, "unsupported path kind for Gitea pulls");
	} break;
	}

	gcli_clear_ptr(&suffix);

	return rc;
}

static int
gitea_pulls_make_url(struct gcli_ctx *ctx, struct gcli_path const *const path,
                     char const *const suffix, char **url)
{
	return gitea_repo_make_url(ctx, path, url, "/issues%s",
	                           suffix ? suffix : "");
}

int
gitea_search_pulls(struct gcli_ctx *ctx, struct gcli_path const *const path,
                   struct gcli_pull_fetch_details const *details,
                   int const max, struct gcli_pull_list *const out)
{
	char *url = NULL, *suffix = NULL;
	int rc = 0;

	struct gcli_fetch_list_ctx fl = {
		.listp = &out->pulls,
		.sizep = &out->pulls_size,
		.parse = (parsefn)(parse_github_pulls),
		.max = max,
	};

	gcli_url_options_append(&suffix, "type", "pulls");
	gcli_url_options_append(&suffix, "state", details->all ? "all" : "open");
	gcli_url_options_append(&suffix, "milestones", details->milestone);
	gcli_url_options_append(&suffix, "created_by", details->author);
	gcli_url_options_append(&suffix, "labels", details->label);
	gcli_url_options_append(&suffix, "q", details->search_term);

	rc = gitea_pulls_make_url(ctx, path, suffix, &url);

	gcli_clear_ptr(&suffix);

	if (rc < 0)
		return rc;

	return gcli_fetch_list(ctx, url, &fl);
}

int
gitea_get_pull(struct gcli_ctx *ctx, struct gcli_path const *const path,
               struct gcli_pull *const out)
{
	int const rc = github_get_pull(ctx, path, out);

	if (rc == 0) {
		/* fix for https://gitlab.com/herrhotzenplotz/gcli/issues/222:
		 *
		 * Sometimes the "reviewers" array contains a single NULL value
		 * that means that this pull request is to be reviewed by the
		 * owners of the repository. */
		for (size_t i = 0; i < out->reviewers_size; ++i) {
			if (out->reviewers[i] == NULL)
				out->reviewers[i] = strdup("Owners");
		}
	}

	return rc;
}

int
gitea_get_pull_commits(struct gcli_ctx *ctx,
                       struct gcli_path const *const path,
                       struct gcli_commit_list *const out)
{
	return github_get_pull_commits(ctx, path, out);
}

int
gitea_pull_submit(struct gcli_ctx *ctx, struct gcli_submit_pull_options *opts)
{
	gcli_warnx(ctx, "In case the following process errors out, see: "
	                "https://github.com/go-gitea/gitea/issues/20175");
	return github_perform_submit_pull(ctx, opts);
}

int
gitea_pull_merge(struct gcli_ctx *ctx, struct gcli_path const *const path,
                 enum gcli_merge_flags const flags)
{
	bool const delete_branch = flags & GCLI_PULL_MERGE_DELETEHEAD;
	bool const squash = flags & GCLI_PULL_MERGE_SQUASH;
	char *url = NULL, *payload = NULL;
	struct gcli_jsongen gen = {0};
	int rc = 0;

	/* Generate URL */
	rc = gitea_pull_make_url(ctx, path, &url, "/merge");
	if (rc < 0)
		return rc;

	/* Generate payload */
	gcli_jsongen_init(&gen);
	gcli_jsongen_begin_object(&gen);
	{
		gcli_jsongen_objmember(&gen, "Do");
		gcli_jsongen_string(&gen, squash ? "squash" : "merge");

		gcli_jsongen_objmember(&gen, "delete_branch_after_merge");
		gcli_jsongen_bool(&gen, delete_branch);
	}
	gcli_jsongen_end_object(&gen);

	payload = gcli_jsongen_to_string(&gen);
	gcli_jsongen_free(&gen);

	rc = gcli_fetch_with_method(ctx, "POST", url, payload, NULL, NULL);

	gcli_clear_ptr(&url);
	gcli_clear_ptr(&payload);

	return rc;
}

static int
gitea_pulls_patch_state(struct gcli_ctx *ctx,
                        struct gcli_path const *const path, char const *state)
{
	char *url = NULL;
	char *data = NULL;
	int rc = 0;

	rc = gitea_pull_make_url(ctx, path, &url, "");
	if (rc < 0)
		return rc;

	data = gcli_asprintf("{ \"state\": \"%s\"}", state);

	rc = gcli_fetch_with_method(ctx, "PATCH", url, data, NULL, NULL);

	gcli_clear_ptr(&data);
	gcli_clear_ptr(&url);

	return rc;
}

int
gitea_pull_close(struct gcli_ctx *ctx, struct gcli_path const *const path)
{
	return gitea_pulls_patch_state(ctx, path, "closed");
}

int
gitea_pull_reopen(struct gcli_ctx *ctx, struct gcli_path const *const path)
{
	return gitea_pulls_patch_state(ctx, path, "open");
}

int
gitea_pull_get_patch(struct gcli_ctx *ctx, FILE *const stream,
                     struct gcli_path const *const path)
{
	char *url = NULL;
	int rc = 0;

	rc = gitea_pull_make_url(ctx, path, &url, ".patch");
	if (rc < 0)
		return rc;

	rc = gcli_curl(ctx, stream, url, NULL);

	gcli_clear_ptr(&url);

	return rc;
}
int
gitea_pull_get_diff(struct gcli_ctx *ctx, FILE *const stream,
                    struct gcli_path const *const path)
{
	char *url = NULL;
	int rc = 0;

	rc = gitea_pull_make_url(ctx, path, &url, ".diff");
	if (rc < 0)
		return rc;

	rc = gcli_curl(ctx, stream, url, NULL);

	gcli_clear_ptr(&url);

	return rc;
}

int
gitea_pull_get_checks(struct gcli_ctx *ctx, struct gcli_path const *const path,
                      struct gcli_pull_checks_list *out)
{
	(void) ctx;
	(void) path;
	(void) out;

	return gcli_error(ctx, "Pull Request checks are not available on Gitea");
}

int
gitea_pull_set_milestone(struct gcli_ctx *ctx,
                         struct gcli_path const *const pull_path,
                         gcli_id milestone_id)
{
	return github_issue_set_milestone(ctx, pull_path, milestone_id);
}

int
gitea_pull_clear_milestone(struct gcli_ctx *ctx,
                           struct gcli_path const *const pull_path)
{
	/* NOTE: The github routine for clearing issues sets the milestone
	 * to null (not the integer zero). However this does not work in
	 * the case of Gitea which clear the milestone by setting it to
	 * the integer value zero. */
	return github_issue_set_milestone(ctx, pull_path, 0);
}

int
gitea_pull_add_reviewer(struct gcli_ctx *ctx,
                        struct gcli_path const *const path,
                        char const *username)
{
	return github_pull_add_reviewer(ctx, path, username);
}

int
gitea_pull_assign(struct gcli_ctx *ctx,
                  struct gcli_path const *const path,
                  char const *username)
{
	return gitea_issue_assign(ctx, path, username);
}

int
gitea_pull_set_title(struct gcli_ctx *ctx, struct gcli_path const *const path,
                     char const *const title)
{
	return github_pull_set_title(ctx, path, title);
}

int
gitea_pull_get_reviews(struct gcli_ctx *ctx,
                       struct gcli_path const *const path,
                       struct gcli_pull_reviews *out)
{
	return github_pull_get_reviews(ctx, path, out);
}

static void
gitea_put_review_comment(struct gcli_jsongen *gen,
                         struct gcli_diff_comment const *comment)
{
	gcli_jsongen_begin_object(gen);
	{
		gcli_jsongen_objmember(gen, "path");
		gcli_jsongen_string(gen, comment->after.filename);

		gcli_jsongen_objmember(gen, "body");
		gcli_jsongen_string(gen, comment->comment);

		if (comment->end_is_in_new) {
			gcli_jsongen_objmember(gen, "new_position");
			gcli_jsongen_number(gen, comment->after.end_row);
			gcli_jsongen_objmember(gen, "old_position");
			gcli_jsongen_number(gen, 0);
		} else {
			gcli_jsongen_objmember(gen, "old_position");
			gcli_jsongen_number(gen, comment->before.end_row);
			gcli_jsongen_objmember(gen, "new_position");
			gcli_jsongen_number(gen, 0);
		}
	}
	gcli_jsongen_end_object(gen);
}

static void
gitea_put_review_comments(struct gcli_jsongen *gen,
                          struct gcli_diff_comments const *comments)
{
	if (TAILQ_EMPTY(comments))
		return;

	gcli_jsongen_objmember(gen, "comments");
	gcli_jsongen_begin_array(gen);
	{
		struct gcli_diff_comment const *comment;

		TAILQ_FOREACH(comment, comments, next)
			gitea_put_review_comment(gen, comment);
	}
	gcli_jsongen_end_array(gen);
}

int
gitea_pull_create_review(struct gcli_ctx *ctx,
                         struct gcli_pull_create_review_details const *details)
{
	int rc = 0;
	char *url = NULL, *payload = NULL;
	struct gcli_jsongen gen = {0};

	/* essentially the same as with github, but notice the 'D'
	 * in approveD ... */
	char const *const state_string[] = {
		[GCLI_REVIEW_ACCEPT_CHANGES] = "APPROVED",
		[GCLI_REVIEW_REQUEST_CHANGES] = "REQUEST_CHANGES",
		[GCLI_REVIEW_COMMENT] = "COMMENT",
	};

	rc = gitea_pull_make_url(ctx, &details->path, &url, "/reviews");
	if (rc < 0)
		return rc;

	if (gcli_jsongen_init(&gen) < 0) {
		rc = gcli_error(ctx, "failed to init JSON generator");
		goto bail;
	}

	gcli_jsongen_begin_object(&gen);
	{
		if (details->body) {
			gcli_jsongen_objmember(&gen, "body");
			gcli_jsongen_string(&gen, details->body);
		}

		gcli_jsongen_objmember(&gen, "event");
		gcli_jsongen_string(&gen, state_string[details->review_state]);

		gitea_put_review_comments(&gen, &details->comments);
	}
	gcli_jsongen_end_object(&gen);

	payload = gcli_jsongen_to_string(&gen);

	rc = gcli_fetch_with_method(ctx, "POST", url, payload, NULL, NULL);

	gcli_jsongen_free(&gen);

bail:
	gcli_clear_ptr(&payload);
	gcli_clear_ptr(&url);

	return rc;
}
