namespace Kit.Helpers.Repository
{
    public interface ISQLiteGlobalVarRepository
    {
        string? Get(FileContentSqlite fileContentSqlite, string key);
        void Set(FileContentSqlite fileContentSqlite, string key, string? value);
    }

    public class SQLiteGlobalVarRepository : ISQLiteGlobalVarRepository
    {
        public SQLiteGlobalVarRepository() { }

        private const string _createIfNotExists = "create table if not exists global_var (key text not null primary key, value text not null); ";
        private const string _getByKey = "select main.value from global_var main where main.key = :key; ";
        private const string _deleteByKey = "delete from global_var where main.key = :key; ";
        private const string _setByKey = "insert into global_var (key, value) values (:key, :value); ";

        public string? Get(FileContentSqlite fileContentSqlite, string key)
        {
            return fileContentSqlite.ConnectionString.PrepareExecute(_createIfNotExists + _getByKey)
                .AsSqlText()
                .WithStrictSyntax()
                .AddParameter("key", key)
                .ExecuteScalar<string?>();
        }


        public void Set(FileContentSqlite fileContentSqlite, string key, string? value)
        {
            string request = _createIfNotExists + _deleteByKey;
            if (string.IsNullOrWhiteSpace(value) == false)
            {
                request += _setByKey;
            }
            else
            {
                value = null;
            }

            fileContentSqlite.ConnectionString.PrepareExecute(request)
                .AsSqlText()
                .WithStrictSyntax()
                .AddParameter("key", key)
                .AddParameterIfNotNull("value", value)
                .ExecuteNonQuery();
        }
    }
}