using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Generic.Contracts.Generics;

namespace Auth.RCL.Services.Utils
{
    public class QueryBuilder
    {
        private readonly StringBuilder _builder;

        public QueryBuilder()
        {
            _builder = new StringBuilder();
        }

        public QueryBuilder AddBase(string baseString)
        {
            _builder.Insert(0, baseString);
            return this;
        }

        public QueryBuilder AddPagination(Pagination pagination)
        {
            if (pagination != null)
            {
                AppendParameter("currentPage", pagination.CurrentPage.Value);
                AppendParameter("pageSize", pagination.PageSize.Value);
            }
            return this;
        }

        public QueryBuilder AddSort(SortModel sort)
        {
            if (sort != null && !string.IsNullOrEmpty(sort.SortBy))
            {
                AppendParameter("Column", sort.SortBy);
                AppendParameter("sortDirection", sort.SortDirection.ToString());
            }
            return this;
        }

        public QueryBuilder AddModelProperties<TModel>(TModel model)
        {
            if (model == null)
                return this;

            var properties = typeof(TModel).GetProperties();
            foreach (var prop in properties)
            {
                var value = prop.GetValue(model)?.ToString();
                if (!string.IsNullOrEmpty(value))
                {
                    AppendParameter(prop.Name.ToLower(), value);
                }
            }
            return this;
        }

        private void AppendParameter(string key, string value)
        {
            if (_builder.Length > 0)
                _builder.Append('&');
            _builder.Append($"{Uri.EscapeDataString(key)}={Uri.EscapeDataString(value)}");
        }

        private void AppendParameter(string key, int value)
        {
            AppendParameter(key, value.ToString());
        }

        public override string ToString() => _builder.ToString();
    }
}
