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

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 创建菜单处理器。
/// </summary>
public sealed class CreateMenuCommandHandler(
    IMenuRepository menuRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<CreateMenuCommand, MenuDefinitionDto>
{
    /// <inheritdoc />
    public async Task<MenuDefinitionDto> Handle(CreateMenuCommand request, CancellationToken cancellationToken)
    {
        // 1. 构造实体
        var tenantId = tenantProvider.GetCurrentTenantId();
        var entity = new MenuDefinition
        {
            TenantId = tenantId,
            ParentId = request.ParentId,
            Name = request.Name.Trim(),
            Path = request.Path.Trim(),
            Component = request.Component.Trim(),
            Title = request.Title.Trim(),
            Icon = request.Icon?.Trim(),
            IsIframe = request.IsIframe,
            Link = string.IsNullOrWhiteSpace(request.Link) ? null : request.Link.Trim(),
            KeepAlive = request.KeepAlive,
            SortOrder = request.SortOrder,
            RequiredPermissions = MenuMapper.JoinCodes(request.RequiredPermissions),
            MetaPermissions = MenuMapper.JoinCodes(request.MetaPermissions),
            MetaRoles = MenuMapper.JoinCodes(request.MetaRoles),
            AuthListJson = request.AuthList.Count == 0
                ? null
                : System.Text.Json.JsonSerializer.Serialize(request.AuthList)
        };

        // 2. 持久化
        await menuRepository.AddAsync(entity, cancellationToken);
        await menuRepository.SaveChangesAsync(cancellationToken);

        // 3. 返回 DTO
        return MenuMapper.ToDto(entity);
    }
}
