using ConstructorAppUI.Dtos.CompanyInfoDtos;
using ConstructorAppUI.Dtos.CompanyInfoVideoDtos;
using ConstructorAppUI.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

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

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

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var client = _httpClientFactory.CreateClient();
            var companyInfoResponse = await client.GetAsync($"{_apiBaseUrl}/api/CompanyInfo");
            var companyInfoVideoResponse = await client.GetAsync($"{_apiBaseUrl}/api/CompanyInfoVideo");

            var viewModel = new HomeCompanyInfoAndVideoViewModel();

            if (companyInfoResponse.IsSuccessStatusCode)
            {
                var companyInfoJson = await companyInfoResponse.Content.ReadAsStringAsync();
                viewModel.CompanyInfo = JsonConvert.DeserializeObject<List<ResultCompanyInfoDto>>(companyInfoJson);
            }

            if (companyInfoVideoResponse.IsSuccessStatusCode)
            {
                var companyInfoVideoJson = await companyInfoVideoResponse.Content.ReadAsStringAsync();
                var companyInfoVideoList = JsonConvert.DeserializeObject<List<ResultCompanyInfoVideoDto>>(companyInfoVideoJson);
                viewModel.CompanyInfoVideo = companyInfoVideoList?.FirstOrDefault();
            }

            return View(viewModel);
        }
    }
}
