using JSMR.Application.Circles.Queries.Search;
using Microsoft.AspNetCore.WebUtilities;
using System.Globalization;

namespace JSMR.UI.Blazor.Filters;

public sealed record CircleFilterState : IFilterState<SearchCirclesRequest>
{
    public string? Keywords { get; init; }
    public CircleStatus? Status { get; init; }
    public int PageNumber { get; init; } = 1;
    public int PageSize { get; init; } = 100;

    public QueryParameters ToQuery()
    {
        QueryParameters query = [];

        query.Set("keywords", Keywords);

        if (Status is not null)
            query.Set("circle", Status.ToString());

        if (PageNumber != 1)
            query.Set("pageNumber", PageNumber.ToString(CultureInfo.InvariantCulture));

        if (PageSize != 100)
            query.Set("pageSize", PageSize.ToString(CultureInfo.InvariantCulture));

        return query;
    }

    public static CircleFilterState FromQuery(string query)
    {
        QueryParameters queryParameters = new(QueryHelpers.ParseQuery(query));

        return new CircleFilterState
        {
            Keywords = queryParameters.GetValue("keywords"),
            Status = queryParameters.GetEnum<CircleStatus>("circle"),
            PageNumber = Math.Max(1, queryParameters.GetInteger("pageNumber", 1)),
            PageSize = queryParameters.GetInteger("pageSize", defaultValue: 100)
        };
    }

    public SearchCirclesRequest ToSearchRequest()
    {
        return new(
            Options: new()
            {
                PageNumber = PageNumber,
                PageSize = PageSize,
                Criteria = new()
                {
                    Name = Keywords,
                    Status = Status
                },
                SortOptions =
                [
                    new(CircleSortField.Name, Application.Common.Search.SortDirection.Ascending)
                ]
            }
        );
    }
}