using Application.Abstractions.Messaging;
﻿using Application.Abstractions.Identity;

namespace Application.Features.Director.User.GetRoles
{
    public sealed class Handler(IIdentityRoleReader roleReader, IIdentityUserReader userReader) : IQueryHandler<Query, Response>
    {
        public async Task<Response> Handle(Query request, CancellationToken ct)
        {
            var user = await userReader.GetUserAsync(request.UserID, ct);
            if (user == null)
            {
                throw new Exception("회원 정보를 찾을 수 없습니다.");
            }

            var roles = await roleReader.GetRolesAsync(ct);
            var userRoleSet = new HashSet<string>(user.Roles, StringComparer.OrdinalIgnoreCase);

            return new Response
            {
                User = user,
                Roles = [..roles.Select(role => new Response.Checkbox
                {
                    DisplayValue = role.Name,
                    IsSelected = role.Name != null && userRoleSet.Contains(role.Name)
                })]
            };
        }
    }
}