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

package setting

import (
	"net/http"

	licenses_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/licenses"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/log"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/templates"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
)

const tplSettingsLicensing templates.TplName = "repo/settings/licensing"

// LicensingSettings displays the licensing settings page.
func LicensingSettings(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.licensing_section")
	ctx.Data["PageIsSettingsLicensing"] = true

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

	ctx.HTML(http.StatusOK, tplSettingsLicensing)
}

// LicensingSettingsPost saves the licensing settings.
func LicensingSettingsPost(ctx *context.Context) {
	repo := ctx.Repo.Repository

	updatePlatform := ctx.FormString("update_platform")
	if updatePlatform == "" {
		updatePlatform = "joomla"
	}

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

	if !enabled {
		// Remove repo-level override so org config takes effect
		if err := licenses_model.DeleteRepoConfig(ctx, repo.ID); err != nil {
			log.Error("DeleteRepoConfig: %v", err)
		}
	} else {
		updateCfg := &licenses_model.UpdateStreamConfig{
			OwnerID:          repo.OwnerID,
			RepoID:           repo.ID,
			Platform:         updatePlatform,
			LicensingEnabled: true,
			RequireKey:       ctx.FormString("require_update_key") == "on",
			DownloadGating:   ctx.FormString("download_gating"),
			SupportURL:       ctx.FormString("support_url"),
			ExtensionName:    ctx.FormString("extension_name"),
			DisplayName:      ctx.FormString("display_name"),
			ExtensionType:    ctx.FormString("extension_type"),
			TargetVersion:    ctx.FormString("target_version"),
			Maintainer:       ctx.FormString("maintainer"),
			PHPMinimum:       ctx.FormString("php_minimum"),
			StreamMode:       "joomla",
		}

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

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