using MediatR;
using TakeoutSaaS.Application.Identity;
using TakeoutSaaS.Application.Identity.Commands;
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 DeleteMenuCommandHandler(IMenuRepository menuRepository)
    : IRequestHandler<DeleteMenuCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteMenuCommand request, CancellationToken cancellationToken)
    {
        // 1. 菜单固定时禁止删除
        if (!MenuPolicy.CanMaintainMenus)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "菜单已固定，禁止删除");
        }

        // 2. 删除目标
        await menuRepository.DeleteAsync(request.Id, cancellationToken);

        // 3. 持久化
        await menuRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回执行结果
        return true;
    }
}
