using ConstructorAppUI.Dtos.HomeBannerDtos;
using ConstructorAppUI.Dtos.SliderDtos;
using ConstructorAppUI.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace ConstructorAppUI.ViewComponents.HomeComponents
{
    public class _HomeBannerAndSliderPartialComponent : ViewComponent
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly string? _apiBaseUrl;

        public _HomeBannerAndSliderPartialComponent(IHttpClientFactory httpClientFactory, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
            _apiBaseUrl = configuration["ApiSettings:BaseUrl"];
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var client = _httpClientFactory.CreateClient();

            var homeBannerResponse = await client.GetAsync($"{_apiBaseUrl}/api/HomeBanner");
            var sliderResponse = await client.GetAsync($"{_apiBaseUrl}/api/Slider");

            var viewModel = new HomeBannerAndSliderViewModel();

            if (homeBannerResponse.IsSuccessStatusCode)
            {
                var bannerJson = await homeBannerResponse.Content.ReadAsStringAsync();
                viewModel.HomeBanners = JsonConvert.DeserializeObject<List<ResultHomeBannerDto>>(bannerJson);
            }

            if (sliderResponse.IsSuccessStatusCode)
            {
                var sliderJson = await sliderResponse.Content.ReadAsStringAsync();
                viewModel.Sliders = JsonConvert.DeserializeObject<List<ResultSliderDto>>(sliderJson);
            }

            return View(viewModel);
        }
    }
}
