package actions

import (
	"context"
	"strings"

	"code.gitea.io/gitea/models/db"
	secret_model "code.gitea.io/gitea/models/secret"
	"xorm.io/builder"
)

type FindSecretsOptions struct {
	db.ListOptions
	OwnerID  int64
	RepoID   int64
	SecretID int64
	Name     string
}

func (opts *FindSecretsOptions) toConds() builder.Cond {
	cond := builder.NewCond()
	if opts.OwnerID > 0 {
		cond = cond.And(builder.Eq{"owner_id": opts.OwnerID})
	}
	if opts.RepoID > 0 {
		cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
	}
	if opts.SecretID != 0 {
		cond = cond.And(builder.Eq{"id": opts.SecretID})
	}
	if opts.Name != "" {
		cond = cond.And(builder.Eq{"name": strings.ToUpper(opts.Name)})
	}

	return cond
}

func FindSecrets(ctx context.Context, opts FindSecretsOptions) ([]*secret_model.Secret, error) {
	var secrets []*secret_model.Secret
	sess := db.GetEngine(ctx)
	if opts.PageSize != 0 {
		sess = db.SetSessionPagination(sess, &opts.ListOptions)
	}
	return secrets, sess.
		Where(opts.toConds()).
		OrderBy("created_unix desc").
		Find(&secrets)
}

func CountSecrets(ctx context.Context, opts *FindSecretsOptions) (int64, error) {
	return db.GetEngine(ctx).Where(opts.toConds()).Count(new(secret_model.Secret))
}

func DeleteSecret(ctx context.Context, secret *secret_model.Secret) error {
	if _, err := db.DeleteByID(ctx, secret.ID, secret); err != nil {
		return err
	}
	return nil
}
