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

package setting

import (
	"net/http"

	updateserver_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/updateserver"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/log"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/templates"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
)

const tplSettingsUpdateServer templates.TplName = "repo/settings/updateserver"

// UpdateServerSettings displays the update server settings page.
func UpdateServerSettings(ctx *context.Context) {
	ctx.Data["Title"] = "Update Server"
	ctx.Data["PageIsSettingsUpdateServer"] = true

	repoCfg, _ := updateserver_model.GetRepoConfig(ctx, ctx.Repo.Repository.ID)
	ctx.Data["RepoUpdateConfig"] = repoCfg

	ctx.HTML(http.StatusOK, tplSettingsUpdateServer)
}

// UpdateServerSettingsPost saves update server visibility and gating settings.
func UpdateServerSettingsPost(ctx *context.Context) {
	repo := ctx.Repo.Repository

	enabled := ctx.FormString("enable_licensing") == "on"

	if !enabled {
		if err := updateserver_model.DeleteRepoConfig(ctx, repo.ID); err != nil {
			log.Error("DeleteRepoConfig: %v", err)
		}
	} else {
		// Load existing config to preserve platform and other fields.
		existing, _ := updateserver_model.GetRepoConfig(ctx, repo.ID)
		platform := "joomla"
		streamMode := "joomla"
		supportURL := ""
		if existing != nil {
			platform = existing.Platform
			streamMode = existing.StreamMode
			supportURL = existing.SupportURL
		}

		updateCfg := &updateserver_model.UpdateStreamConfig{
			OwnerID:          repo.OwnerID,
			RepoID:           repo.ID,
			Platform:         platform,
			LicensingEnabled: true,
			RequireKey:       ctx.FormString("require_update_key") == "on",
			DownloadGating:   ctx.FormString("download_gating"),
			FeedVisibility:   ctx.FormString("feed_visibility"),
			SupportURL:       supportURL,
			StreamMode:       streamMode,
		}

		if err := updateserver_model.SaveConfig(ctx, updateCfg); err != nil {
			log.Error("SaveConfig: %v", err)
			ctx.ServerError("SaveConfig", err)
			return
		}
	}

	ctx.Flash.Success("Update server settings saved")
	ctx.Redirect(ctx.Repo.RepoLink + "/settings/updateserver")
}
