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

// UpdateIssueCustomType handles POST to set a custom type on an issue.
func UpdateIssueCustomType(ctx *context.Context) {
	issueID := ctx.PathParamInt64("id")
	typeID := ctx.FormInt64("type_id")

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

	if typeID > 0 {
		typeDef, err := issues_model.GetIssueTypeDefByID(ctx, typeID)
		if err != nil {
			ctx.ServerError("GetIssueTypeDefByID", err)
			return
		}
		if typeDef.OrgID != ctx.Repo.Repository.OwnerID {
			ctx.NotFound(nil)
			return
		}
	}

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

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