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

package org

import (
	"net/http"
	"strings"

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

const tplSettingsUpdateStreams templates.TplName = "org/settings/update_streams"

// SettingsUpdateStreams shows the org-level update stream settings.
func SettingsUpdateStreams(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("org.settings.update_streams")
	ctx.Data["PageIsOrgSettings"] = true
	ctx.Data["PageIsSettingsUpdateStreams"] = true

	orgID := ctx.Org.Organization.ID

	cfg, err := updateserver_model.GetOrgConfig(ctx, orgID)
	if err != nil {
		ctx.ServerError("GetOrgConfig", err)
		return
	}
	ctx.Data["StreamConfig"] = cfg
	ctx.Data["EffectiveStreams"] = cfg.GetActiveStreams()

	ctx.HTML(http.StatusOK, tplSettingsUpdateStreams)
}

// SettingsUpdateStreamsPost saves the org-level update stream settings.
func SettingsUpdateStreamsPost(ctx *context.Context) {
	orgID := ctx.Org.Organization.ID

	cfg := &updateserver_model.UpdateStreamConfig{
		OwnerID:          orgID,
		RepoID:           0,
		StreamMode:       ctx.FormString("stream_mode"),
		Platform:         ctx.FormString("platform"),
		CustomStreams:     ctx.FormString("custom_streams"),
		LicensingEnabled: ctx.FormString("licensing_enabled") == "on",
		RequireKey:       ctx.FormString("require_key") == "on",
		FeedVisibility:   ctx.FormString("feed_visibility"),
		DownloadGating:   ctx.FormString("download_gating"),
		SupportURL:       ctx.FormString("support_url"),
		KeyPrefix:        strings.ToUpper(strings.TrimSpace(ctx.FormString("key_prefix"))),
		ExtensionName:    ctx.FormString("extension_name"),
		Description:      ctx.FormString("feed_description"),
		ExtensionType:    ctx.FormString("extension_type"),
		Maintainer:       ctx.FormString("maintainer"),
		MaintainerURL:    ctx.FormString("maintainer_url"),
		InfoURL:          ctx.FormString("info_url"),
		TargetVersion:    ctx.FormString("target_version"),
		PHPMinimum:       ctx.FormString("php_minimum"),
	}

	if cfg.StreamMode == "" {
		cfg.StreamMode = "joomla"
	}

	if err := updateserver_model.SaveConfig(ctx, cfg); err != nil {
		ctx.ServerError("SaveConfig", err)
		return
	}

	ctx.Flash.Success(ctx.Tr("org.settings.update_streams_saved"))
	ctx.Redirect(ctx.Org.OrgLink + "/settings/update-streams")
}
