// Copyright 2026 Moko Consulting <hello@mokoconsulting.tech>
// SPDX-License-Identifier: GPL-3.0-or-later

package repo

import (
	"fmt"
	"net/http"

	issues_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/issues"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
)

// UpdateIssueCustomPriority handles POST to set a custom priority on an issue.
func UpdateIssueCustomPriority(ctx *context.Context) {
	issueID := ctx.PathParamInt64("id")
	priorityID := ctx.FormInt64("priority_id")

	issue, err := issues_model.GetIssueByID(ctx, issueID)
	if err != nil {
		ctx.ServerError("GetIssueByID", err)
		return
	}

	// Validate the priority belongs to this repo's org.
	if priorityID > 0 {
		priorityDef, err := issues_model.GetIssuePriorityDefByID(ctx, priorityID)
		if err != nil {
			ctx.ServerError("GetIssuePriorityDefByID", err)
			return
		}
		if priorityDef.OrgID != ctx.Repo.Repository.OwnerID {
			ctx.NotFound(nil)
			return
		}
	}

	if err := issues_model.SetIssuePriorityID(ctx, issueID, priorityID); err != nil {
		ctx.ServerError("SetIssuePriorityID", err)
		return
	}

	ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
}
