using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 删除公告处理器。
/// </summary>
public sealed class DeleteTenantAnnouncementCommandHandler(
    ITenantAnnouncementRepository announcementRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteTenantAnnouncementCommand, bool>
{
    /// <summary>
    /// 处理删除公告请求。
    /// </summary>
    /// <param name="request">删除命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(DeleteTenantAnnouncementCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验租户上下文（租户端禁止跨租户）
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 兼容旧调用：若传入 TenantId，则必须与当前租户一致
        if (request.TenantId > 0 && request.TenantId != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "无权删除其他租户公告");
        }

        // 3. (空行后) 删除公告
        await announcementRepository.DeleteAsync(currentTenantId, request.AnnouncementId, cancellationToken);
        await announcementRepository.SaveChangesAsync(cancellationToken);

        // 4. (空行后) 返回执行结果
        return true;
    }
}
