using System.Text.Json;
using bitforum.Constants;
using bitforum.Models;
using bitforum.Models.Views;

namespace bitforum.Middleware
{
    public class Common
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;

        public Common(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            AppConfig? appConfig = null;

            try
            {
                appConfig = _configuration.GetSection("AppConfig").Get<AppConfig>(); ;
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"JSON Parsing Error: {ex.Message}");
            }

            context.Items["layoutViewModel"] = new LayoutViewModel
            {
                // 환경 변수 가져오기
                AppConfig = appConfig,

                // 메뉴 데이터 가져오기
                Menus = Menus.GetMenus()
            };

            await _next(context);
        }
    }
}
