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

package setting

import (
	"encoding/json"
	"fmt"
	"net/http"

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

const tplSettingsMetadata templates.TplName = "repo/settings/metadata"

// Metadata displays the repo metadata page (repo-scoped custom field values).
func Metadata(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.metadata")
	ctx.Data["PageIsSettingsMetadata"] = true

	ownerID := ctx.Repo.Repository.OwnerID
	repoID := ctx.Repo.Repository.ID

	fields, _ := issues_model.GetCustomFieldsByOwner(ctx, ownerID, issues_model.CustomFieldScopeRepo)
	ctx.Data["CustomFieldDefs"] = fields

	values := make(map[int64]string)
	fieldOptions := make(map[int64][]string)
	if len(fields) > 0 {
		values, _ = issues_model.GetCustomFieldValuesMap(ctx, repoID)
		for _, f := range fields {
			if f.Options != "" {
				var opts []string
				if err := json.Unmarshal([]byte(f.Options), &opts); err == nil {
					fieldOptions[f.ID] = opts
				}
			}
		}
	}
	ctx.Data["CustomFieldValues"] = values
	ctx.Data["CustomFieldOptions"] = fieldOptions

	ctx.HTML(http.StatusOK, tplSettingsMetadata)
}

// MetadataPost saves repo-scoped custom field values.
func MetadataPost(ctx *context.Context) {
	repoID := ctx.Repo.Repository.ID
	ownerID := ctx.Repo.Repository.OwnerID

	fields, _ := issues_model.GetCustomFieldsByOwner(ctx, ownerID, issues_model.CustomFieldScopeRepo)
	for _, f := range fields {
		val := ctx.Req.FormValue(fmt.Sprintf("field_%d", f.ID))
		if err := issues_model.SetCustomFieldValue(ctx, repoID, f.ID, val); err != nil {
			ctx.ServerError("SetCustomFieldValue", err)
			return
		}
	}

	ctx.Flash.Success(ctx.Tr("repo.settings.metadata_saved"))
	ctx.Redirect(ctx.Repo.RepoLink + "/settings/metadata")
}
