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 GetRoleTemplateQueryHandler(IRoleTemplateRepository roleTemplateRepository)
    : IRequestHandler<GetRoleTemplateQuery, RoleTemplateDto?>
{
    /// <inheritdoc />
    public async Task<RoleTemplateDto?> Handle(GetRoleTemplateQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询模板
        var template = await roleTemplateRepository.FindByCodeAsync(request.TemplateCode, cancellationToken);
        if (template == null)
        {
            return null;
        }

        // 2. 查询模板权限
        var permissions = await roleTemplateRepository.GetPermissionsAsync(template.Id, cancellationToken);
        var codes = permissions.Select(x => x.PermissionCode).ToArray();

        // 3. 返回 DTO
        return TemplateMapper.ToDto(template, codes);
    }
}
