package actions

import (
	"context"
	"regexp"
	"strings"
	"sync"

	secret_model "code.gitea.io/gitea/models/secret"
	hat_actions_model "code.gitlink.org.cn/Gitlink/gitea_hat.git/models/actions"

	"code.gitea.io/gitea/modules/util"
)

var globalVars = sync.OnceValue(func() (ret struct {
	namePattern, forbiddenPrefixPattern *regexp.Regexp
},
) {
	ret.namePattern = regexp.MustCompile("(?i)^[A-Z_][A-Z0-9_]*$")
	ret.forbiddenPrefixPattern = regexp.MustCompile("(?i)^GIT(EA|HUB)_")
	return ret
})

func ValidateName(name string) error {
	vars := globalVars()
	if !vars.namePattern.MatchString(name) ||
		vars.forbiddenPrefixPattern.MatchString(name) ||
		strings.EqualFold(name, "CI") /* CI is always set to true in GitHub Actions*/ {
		return util.NewInvalidArgumentErrorf("invalid variable or secret name")
	}
	return nil
}

func CreateSecret(ctx context.Context, ownerID, repoID int64, name, data string) (*secret_model.Secret, error) {
	if err := ValidateName(name); err != nil {
		return nil, err
	}

	s, err := secret_model.InsertEncryptedSecret(ctx, ownerID, repoID, name, data)
	if err != nil {
		return nil, err
	}

	return s, nil
}

func UpdateSecret(ctx context.Context, ownerID, repoID int64, name, data string) (bool, error) {
	if err := ValidateName(name); err != nil {
		return false, err
	}

	s, err := GetSecret(ctx, hat_actions_model.FindSecretsOptions{
		OwnerID: ownerID,
		RepoID:  repoID,
		Name:    name,
	})
	if err != nil {
		return false, err
	}

	if s == nil {
		return false, util.NewNotExistErrorf("secret not found")
	}

	err = secret_model.UpdateSecret(ctx, s.ID, data)
	if err != nil {
		return false, err
	}

	return true, nil
}

func GetSecret(ctx context.Context, opts hat_actions_model.FindSecretsOptions) (*secret_model.Secret, error) {
	vars, err := hat_actions_model.FindSecrets(ctx, opts)
	if err != nil {
		return nil, err
	}
	if len(vars) != 1 {
		return nil, util.NewNotExistErrorf("variable not found")
	}
	return vars[0], nil
}

func DeleteSecretByName(ctx context.Context, ownerID, repoID int64, name string) error {
	s, err := GetSecret(ctx, hat_actions_model.FindSecretsOptions{
		OwnerID: ownerID,
		RepoID:  repoID,
		Name:    name,
	})
	if err != nil {
		return err
	}

	return hat_actions_model.DeleteSecret(ctx, s)
}

func DeleteSecretByID(ctx context.Context, secretID int64) error {
	s, err := GetSecret(ctx, hat_actions_model.FindSecretsOptions{
		SecretID: secretID,
	})
	if err != nil {
		return err
	}
	return hat_actions_model.DeleteSecret(ctx, s)
}
