using MediatR;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Application.Identity.Queries;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 角色模板权限查询处理器。
/// </summary>
public sealed class RoleTemplatePermissionsQueryHandler(IRoleTemplateRepository roleTemplateRepository)
    : IRequestHandler<RoleTemplatePermissionsQuery, IReadOnlyList<PermissionTemplateDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<PermissionTemplateDto>> Handle(RoleTemplatePermissionsQuery request, CancellationToken cancellationToken)
    {
        // 1. 校验模板存在
        var template = await roleTemplateRepository.FindByCodeAsync(request.TemplateCode, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, $"角色模板 {request.TemplateCode} 不存在");

        // 2. 查询模板权限
        var permissions = await roleTemplateRepository.GetPermissionsAsync(template.Id, cancellationToken);

        // 3. 映射 DTO
        var dto = permissions
            .Where(x => !string.IsNullOrWhiteSpace(x.PermissionCode))
            .Select(x => new PermissionTemplateDto
            {
                Code = x.PermissionCode,
                Name = x.PermissionCode,
                Description = x.PermissionCode
            })
            .ToList();

        // 4. 返回权限列表
        return dto;
    }
}
