// 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"
)

// UpdateIssueCustomField handles POST to set a custom field value on an issue.
func UpdateIssueCustomField(ctx *context.Context) {
	issueID := ctx.PathParamInt64("id")
	fieldID := ctx.PathParamInt64("field_id")
	value := ctx.FormString("value")

	// Look up issue to get the index for redirect.
	issue, err := issues_model.GetIssueByID(ctx, issueID)
	if err != nil {
		ctx.ServerError("GetIssueByID", err)
		return
	}

	if err := issues_model.SetCustomFieldValue(ctx, issueID, fieldID, value); err != nil {
		ctx.ServerError("SetCustomFieldValue", err)
		return
	}

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