// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package secrets

import (
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/db"
	secret_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/secret"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/log"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/util"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/web"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/forms"
	secret_service "code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/secrets"
)

func SetSecretsContext(ctx *context.Context, ownerID, repoID int64) {
	secrets, err := db.Find[secret_model.Secret](ctx, secret_model.FindSecretsOptions{OwnerID: ownerID, RepoID: repoID})
	if err != nil {
		ctx.ServerError("FindSecrets", err)
		return
	}

	ctx.Data["Secrets"] = secrets
	ctx.Data["DataMaxLength"] = secret_model.SecretDataMaxLength
	ctx.Data["DescriptionMaxLength"] = secret_model.SecretDescriptionMaxLength

	// MokoGitea: when viewing repo secrets, also show inherited org secrets
	if repoID > 0 && ctx.Repo != nil && ctx.Repo.Repository != nil {
		orgSecrets, err := db.Find[secret_model.Secret](ctx, secret_model.FindSecretsOptions{OwnerID: ctx.Repo.Repository.OwnerID})
		if err != nil {
			log.Error("FindOrgSecrets failed: %v", err)
		} else if len(orgSecrets) > 0 {
			// Build a set of repo secret names to detect overrides
			repoSecretNames := make(map[string]bool, len(secrets))
			for _, s := range secrets {
				repoSecretNames[s.Name] = true
			}
			ctx.Data["OrgSecrets"] = orgSecrets
			ctx.Data["RepoSecretNames"] = repoSecretNames
			if err := ctx.Repo.Repository.LoadOwner(ctx); err == nil {
				ctx.Data["OrgSecretsLink"] = ctx.Repo.Repository.Owner.HTMLURL(ctx) + "/settings/actions/secrets"
			}
		}
	}
}

func PerformSecretsPost(ctx *context.Context, ownerID, repoID int64, redirectURL string) {
	form := web.GetForm(ctx).(*forms.AddSecretForm)

	s, _, err := secret_service.CreateOrUpdateSecret(ctx, ownerID, repoID, form.Name, util.NormalizeStringEOL(form.Data), form.Description)
	if err != nil {
		log.Error("CreateOrUpdateSecret failed: %v", err)
		ctx.JSONError(ctx.Tr("secrets.save_failed"))
		return
	}

	ctx.Flash.Success(ctx.Tr("secrets.save_success", s.Name))
	ctx.JSONRedirect(redirectURL)
}

func PerformSecretsDelete(ctx *context.Context, ownerID, repoID int64, redirectURL string) {
	id := ctx.FormInt64("id")

	err := secret_service.DeleteSecretByID(ctx, ownerID, repoID, id)
	if err != nil {
		log.Error("DeleteSecretByID(%d) failed: %v", id, err)
		ctx.JSONError(ctx.Tr("secrets.deletion.failed"))
		return
	}

	ctx.Flash.Success(ctx.Tr("secrets.deletion.success"))
	ctx.JSONRedirect(redirectURL)
}
