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

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 角色详情查询处理器。
/// </summary>
public sealed class RoleDetailQueryHandler(
    IRoleRepository roleRepository,
    IRolePermissionRepository rolePermissionRepository,
    IPermissionRepository permissionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<RoleDetailQuery, RoleDetailDto?>
{
    /// <inheritdoc />
    public async Task<RoleDetailDto?> Handle(RoleDetailQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并查询角色
        var tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();
        var role = await roleRepository.FindByIdAsync(request.RoleId, tenantId, cancellationToken);
        if (role is null)
        {
            return null;
        }

        // 2. 查询角色权限关系
        var relations = await rolePermissionRepository.GetByRoleIdsAsync(tenantId, new[] { role.Id }, cancellationToken);
        var permissionIds = relations.Select(x => x.PermissionId).ToArray();

        // 3. 拉取权限实体
        var permissions = permissionIds.Length == 0
            ? Array.Empty<Domain.Identity.Entities.Permission>()
            : await permissionRepository.GetByIdsAsync(tenantId, permissionIds, cancellationToken);

        // 4. 映射 DTO
        var permissionDtos = permissions
            .Select(x => new PermissionDto
            {
                Id = x.Id,
                TenantId = x.TenantId,
                ParentId = x.ParentId,
                SortOrder = x.SortOrder,
                Type = x.Type,
                Code = x.Code,
                Name = x.Name,
                Description = x.Description
            })
            .ToList();

        return new RoleDetailDto
        {
            Id = role.Id,
            TenantId = role.TenantId,
            Name = role.Name,
            Code = role.Code,
            Description = role.Description,
            Permissions = permissionDtos
        };
    }
}
