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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 更新公告处理器。
/// </summary>
public sealed class UpdateTenantAnnouncementCommandHandler(ITenantAnnouncementRepository announcementRepository)
    : IRequestHandler<UpdateTenantAnnouncementCommand, TenantAnnouncementDto?>
{
    public async Task<TenantAnnouncementDto?> Handle(UpdateTenantAnnouncementCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验输入
        if (string.IsNullOrWhiteSpace(request.Title) || string.IsNullOrWhiteSpace(request.Content))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "公告标题和内容不能为空");
        }

        // 2. 查询公告
        var announcement = await announcementRepository.FindByIdAsync(request.TenantId, request.AnnouncementId, cancellationToken);
        if (announcement == null)
        {
            return null;
        }

        // 3. 更新字段
        announcement.Title = request.Title.Trim();
        announcement.Content = request.Content;
        announcement.AnnouncementType = request.AnnouncementType;
        announcement.Priority = request.Priority;
        announcement.EffectiveFrom = request.EffectiveFrom;
        announcement.EffectiveTo = request.EffectiveTo;
        announcement.IsActive = request.IsActive;

        // 4. 持久化
        await announcementRepository.UpdateAsync(announcement, cancellationToken);
        await announcementRepository.SaveChangesAsync(cancellationToken);

        // 5. 返回 DTO
        return announcement.ToDto(false, null);
    }
}
