namespace Netina.Api.Controllers;

public class SearchController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("Search").MapGroup("api/search");

        group.MapGet("", SearchAsync)
            .WithDisplayName("Search Async")
            .HasApiVersion(1.0);

        group.MapGet("/thumb", SearchThumbAsync)
            .WithDisplayName("Thumb Search Async")
            .HasApiVersion(1.0);

        group.MapGet("zarehbin", ZarehbinAsync)
            .WithDisplayName("Search Async")
            .HasApiVersion(1.0);

        group.MapGet("torob", TorobAsync)
            .WithDisplayName("Get Torob Product Async")
            .HasApiVersion(1.0);
    }

    private async Task<IResult> SearchThumbAsync([FromQuery] string name, [FromServices] ISearchService searchService, CancellationToken cancellationToken)
        => TypedResults.Ok(await searchService.ThumbSearchAsync(name, cancellationToken));

    private async Task<IResult> SearchAsync([FromQuery] string name, [FromServices] ISearchService searchService, CancellationToken cancellationToken)
        => TypedResults.Ok(await searchService.SearchAsync(name, cancellationToken));

    private async Task<IResult> ZarehbinAsync([FromQuery] string? product_id, [FromQuery] int? page, [FromServices] ISearchService searchService, CancellationToken cancellationToken)
    {
        if (product_id == null)
        {
            if (page == null)
                return TypedResults.Ok(await searchService.ZarehbinAsync(0, cancellationToken));
            else
                return TypedResults.Ok(await searchService.ZarehbinAsync(page.Value, cancellationToken));
        }
        else
            return TypedResults.Ok(await searchService.ZarehbinAsync(Guid.Parse(product_id), cancellationToken));
    }

    private async Task<IResult> TorobAsync([FromQuery] int page, [FromServices] IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(new GetTorobProductsQuery(page),cancellationToken));
}