using MediatR;
using Knot.Shared.Kernel.Constants;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using System;
using System.Threading.Tasks;

namespace Knot.Modules.Klipy.Presentation.Endpoints;

/// <summary>
/// Регистрация эндпоинтов для сервиса Klipy.
/// </summary>
public static class KlipyEndpoints
{
    public static void MapKlipyEndpoints(this WebApplication app)
    {
        var group = app.MapGroup(Routes.ApiKlipy).RequireAuthorization();

        group.MapGet("/trending", async ([FromQuery] int page, ISender sender, CancellationToken ct) =>
        {
            var result = await sender.Send(new Knot.Modules.Klipy.Application.Klipy.Queries.GetTrendingGifsQuery(page > 0 ? page : 1), ct);
            return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(new { error = result.Error.Description });
        });

        group.MapGet("/search", async ([FromQuery] string q, [FromQuery] int page, ISender sender, CancellationToken ct) =>
        {
            var result = await sender.Send(new Knot.Modules.Klipy.Application.Klipy.Queries.SearchGifsQuery(q, page > 0 ? page : 1), ct);
            return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(new { error = result.Error.Description });
        });

        group.MapGet("/recent", async ([FromQuery] int page, ISender sender, CancellationToken ct) =>
        {
            var result = await sender.Send(new Knot.Modules.Klipy.Application.Klipy.Queries.GetRecentGifsQuery(page > 0 ? page : 1), ct);
            return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(new { error = result.Error.Description });
        });

        group.MapGet("/categories", async ([FromQuery] string? countryCode, ISender sender, CancellationToken ct) =>
        {
            var result = await sender.Send(new Knot.Modules.Klipy.Application.Klipy.Queries.GetGifCategoriesQuery(countryCode ?? "RU"), ct);
            return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(new { error = result.Error.Description });
        });

        group.MapPost("/{gifId}/share", async (string gifId, [FromQuery] string? q, ISender sender, CancellationToken ct) =>
        {
            var result = await sender.Send(new Knot.Modules.Klipy.Application.Klipy.Commands.MarkGifSharedCommand(gifId, q ?? ""), ct);
            return result.IsSuccess ? Results.Ok() : Results.BadRequest(new { error = result.Error.Description });
        });
    }
}
