using Netina.Domain.Enums;
using Netina.Domain.MartenEntities.Settings;

namespace Netina.Api.Controllers;

public class WebSiteController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("WebSite").MapGroup("api/website");

        group.MapGet("/navbar", GetNavBarItemsAsync)
            .WithDisplayName("Get NavBar Items")
            .HasApiVersion(1.0);

        group.MapGet("/catelog", GetCatalogAsync)
            .WithDisplayName("Get Catalog Items")
            .HasApiVersion(1.0);

        group.MapGet("/banner", GetBannerAsync)
            .WithDisplayName("Get Banner Items")
            .HasApiVersion(1.0);
    }

    private async Task<IResult> GetNavBarItemsAsync([FromServices] IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(new GetWebSiteNavBarCommand(),cancellationToken));

    private async Task<IResult> GetCatalogAsync([FromServices] ISettingService settingService, CancellationToken cancellationToken)
    {
        var setting = await settingService.GetSettingAsync(nameof(PersonalizationSetting), cancellationToken);
        if (setting is PersonalizationSetting personalizationSetting)
        {
            return TypedResults.Ok(personalizationSetting.Catalog);
        }

        throw new BaseApiException(ApiResultStatusCode.BadRequest, "Catalogs not found");
    }

    private async Task<IResult> GetBannerAsync([FromQuery]BannerSection? section,[FromServices] ISettingService settingService, CancellationToken cancellationToken)
    {
        var setting = await settingService.GetSettingAsync(nameof(PersonalizationSetting), cancellationToken);
        if (setting is not PersonalizationSetting personalizationSetting)
            throw new BaseApiException(ApiResultStatusCode.BadRequest, "Catalogs not found");
        if (section != null)
            return TypedResults.Ok(personalizationSetting.Banners.Where(b => b.Section == section));
        return TypedResults.Ok(personalizationSetting.Banners);

    }
}