using CartWise.Application.Interfaces;
using CartWise.Infrastructure.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;

namespace CartWise.Web.Authorization;

public class HouseholdMemberAuthorizationHandler : AuthorizationHandler<HouseholdMemberRequirement, Guid>
{
    private readonly IHouseholdService _householdService;
    private readonly UserManager<ApplicationUser> _userManager;

    public HouseholdMemberAuthorizationHandler(IHouseholdService householdService, UserManager<ApplicationUser> userManager)
    {
        _householdService = householdService;
        _userManager = userManager;
    }

    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        HouseholdMemberRequirement requirement,
        Guid householdId)
    {
        var userId = _userManager.GetUserId(context.User);
        if (userId is null)
        {
            return;
        }

        if (await _householdService.IsMemberAsync(householdId, userId))
        {
            context.Succeed(requirement);
        }
    }
}
