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

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 更新权限处理器。
/// </summary>
public sealed class UpdatePermissionCommandHandler(
    IPermissionRepository permissionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<UpdatePermissionCommand, PermissionDto?>
{
    /// <summary>
    /// 执行权限更新。
    /// </summary>
    /// <param name="request">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新后的权限 DTO 或 null。</returns>
    public async Task<PermissionDto?> Handle(UpdatePermissionCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并查询权限
        var tenantId = tenantProvider.GetCurrentTenantId();
        var permission = await permissionRepository.FindByIdAsync(request.PermissionId, tenantId, cancellationToken);
        if (permission == null)
        {
            return null;
        }

        // 2. 更新字段
        var normalizedType = string.IsNullOrWhiteSpace(request.Type)
            ? "leaf"
            : request.Type.Trim().ToLowerInvariant();
        normalizedType = normalizedType is "group" or "leaf" ? normalizedType : "leaf";
        var parentId = request.ParentId > 0 && request.ParentId != permission.Id
            ? request.ParentId
            : 0;
        var sortOrder = request.SortOrder < 0 ? 0 : request.SortOrder;
        permission.ParentId = parentId;
        permission.SortOrder = sortOrder;
        permission.Type = normalizedType;
        permission.Name = request.Name;
        permission.Description = request.Description;

        // 3. 持久化
        await permissionRepository.UpdateAsync(permission, cancellationToken);
        await permissionRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return new PermissionDto
        {
            Id = permission.Id,
            TenantId = permission.TenantId,
            ParentId = permission.ParentId,
            SortOrder = permission.SortOrder,
            Type = permission.Type,
            Name = permission.Name,
            Code = permission.Code,
            Description = permission.Description
        };
    }
}
