using SharedKernel;
using SharedKernel.Constants;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Identity;
using Infrastructure.Persistence.Identity;
using System.Security.Claims;

namespace Admin.Pages.Shared.Layout
{
    public class LayoutDataProvider : ILayoutDataProvider
    {
        private readonly AppSettings _settings;
        private readonly IAuthorizationService _authorizationService;
        private readonly UserManager<ApplicationUser> _userManager;

        public LayoutDataProvider(IOptions<AppSettings> options, IAuthorizationService authorizationService, UserManager<ApplicationUser> userManager)
        {
            _settings = options.Value;
            _authorizationService = authorizationService;
            _userManager = userManager;
        }

        public async Task<LayoutViewModel> CreateAsync(HttpContext context)
        {
            var principal = context.User;

            var appUser = await _userManager.GetUserAsync(principal);

            // Identity 권한/역할 기반 메뉴 필터링
            var filteredMenus = await Menus.FilterForUserAsync(principal, _authorizationService);

            return new LayoutViewModel
            {
                UserName = appUser?.UserName ?? appUser?.Email ?? principal.Identity?.Name ?? string.Empty,
                Role = principal.FindFirst(ClaimTypes.Role)?.Value ?? principal.FindFirst("role")?.Value ?? string.Empty,
                AppSettings = _settings,
                Menus = filteredMenus
            };
        }
    }
}