package actions

import (
	"context"

	actions_model "code.gitea.io/gitea/models/actions"
	"code.gitea.io/gitea/modules/util"

	secret_service "code.gitea.io/gitea/services/secrets"
	hat_actions_model "code.gitlink.org.cn/Gitlink/gitea_hat.git/models/actions"
	hat_util "code.gitlink.org.cn/Gitlink/gitea_hat.git/modules/util"
)

func CreateVariable(ctx context.Context, ownerID, repoID int64, name, data string) (*actions_model.ActionVariable, error) {
	if err := secret_service.ValidateName(name); err != nil {
		return nil, err
	}

	v, err := actions_model.InsertVariable(ctx, ownerID, repoID, name, hat_util.ReserveLineBreakForTextarea(data))
	if err != nil {
		return nil, err
	}

	return v, nil
}

func UpdateVariableNameData(ctx context.Context, variable *actions_model.ActionVariable) (bool, error) {
	if err := secret_service.ValidateName(variable.Name); err != nil {
		return false, err
	}

	variable.Data = hat_util.ReserveLineBreakForTextarea(variable.Data)

	return actions_model.UpdateVariable(ctx, variable)
}

func DeleteVariableByID(ctx context.Context, variableID int64) error {
	v, err := GetVariable(ctx, hat_actions_model.FindVariablesOpts{
		IDs: []int64{variableID},
	})
	if err != nil {
		return err
	}
	return hat_actions_model.DeleteVariable(ctx, v)
}

func DeleteVariableByName(ctx context.Context, ownerID, repoID int64, name string) error {
	v, err := GetVariable(ctx, hat_actions_model.FindVariablesOpts{
		OwnerID: ownerID,
		RepoID:  repoID,
		Name:    name,
	})
	if err != nil {
		return err
	}

	return hat_actions_model.DeleteVariable(ctx, v)
}

func GetVariable(ctx context.Context, opts hat_actions_model.FindVariablesOpts) (*actions_model.ActionVariable, error) {
	vars, err := hat_actions_model.FindVariables(ctx, opts)
	if err != nil {
		return nil, err
	}
	if len(vars) != 1 {
		return nil, util.NewNotExistErrorf("variable not found")
	}
	return vars[0], nil
}
