using Brizco.Core.MartenServices.Abstracts;
using System.Text.Json;

namespace Brizco.Api.Controllers;

public class BrewController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("Brews")
            .MapGroup("api/brew")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());

        group.MapGet("{brewName}/latest", GetLatestBrewAsync)
            .WithDisplayName("Get Latest Brew")
            .WithDescription("Get latest brew that has been set for day , you have pass recipe name in route")
            .HasApiVersion(1.0);

        group.MapGet("{brewName}", GetBrewAsync)
            .WithDisplayName("Get Brew")
            .WithDescription("Get brew that has been set for days , you have pass recipe name in route")
            .HasApiVersion(1.0);

        group.MapPost("{brewName}", AddBrewAsync)
            .WithDisplayName("Add Brew")
            .WithDescription("Add latest brew that has been set for day , you have pass recipe model")
            .HasApiVersion(1.0);
    }

    private async Task<IResult> GetLatestBrewAsync([FromRoute] string brewName, [FromServices] IBrewService brewService, CancellationToken cancellationToken)
        => TypedResults.Ok(await brewService.GetLastBrewAsync(brewName, cancellationToken));

    private async Task<IResult> GetBrewAsync([FromRoute] string brewName, [FromServices] IBrewService brewService, CancellationToken cancellationToken)
        => TypedResults.Ok(await brewService.GetBrewAsync(brewName, cancellationToken));

    private async Task<IResult> AddBrewAsync([FromRoute] string brewName, [FromBody] JsonDocument recipeObj, [FromServices] IBrewService brewService,  CancellationToken cancellationToken)
    {
        await brewService.AddBrewAsync(brewName, recipeObj, cancellationToken);
        return TypedResults.Ok();
    }
}