using MediatR;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Application.Identity.Queries;
using TakeoutSaaS.Domain.Identity.Repositories;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 角色模板列表查询处理器。
/// </summary>
public sealed class ListRoleTemplatesQueryHandler(IRoleTemplateRepository roleTemplateRepository)
    : IRequestHandler<ListRoleTemplatesQuery, IReadOnlyList<RoleTemplateDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<RoleTemplateDto>> Handle(ListRoleTemplatesQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询模板与权限映射
        var templates = await roleTemplateRepository.GetAllAsync(request.IsActive, cancellationToken);
        var permissionsMap = await roleTemplateRepository.GetPermissionsAsync(templates.Select(t => t.Id), cancellationToken);

        // 2. 排序并映射 DTO
        var dtos = templates
            .OrderBy(template => template.TemplateCode, StringComparer.OrdinalIgnoreCase)
            .Select(template =>
            {
                var codes = permissionsMap.TryGetValue(template.Id, out var perms)
                    ? (IReadOnlyCollection<string>)perms.Select(p => p.PermissionCode).ToArray()
                    : Array.Empty<string>();
                return TemplateMapper.ToDto(template, codes);
            })
            .ToArray();

        // 3. 返回结果
        return dtos;
    }
}
