using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Entities;
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 CreateTenantAnnouncementCommandHandler(ITenantAnnouncementRepository announcementRepository)
    : IRequestHandler<CreateTenantAnnouncementCommand, TenantAnnouncementDto>
{
    /// <summary>
    /// 处理创建租户公告请求。
    /// </summary>
    /// <param name="request">创建命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>公告 DTO。</returns>
    public async Task<TenantAnnouncementDto> Handle(CreateTenantAnnouncementCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验标题与内容
        if (string.IsNullOrWhiteSpace(request.Title) || string.IsNullOrWhiteSpace(request.Content))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "公告标题和内容不能为空");
        }

        // 2. 构建公告实体
        var announcement = new TenantAnnouncement
        {
            TenantId = request.TenantId,
            Title = request.Title.Trim(),
            Content = request.Content,
            AnnouncementType = request.AnnouncementType,
            Priority = request.Priority,
            EffectiveFrom = request.EffectiveFrom,
            EffectiveTo = request.EffectiveTo,
            IsActive = request.IsActive
        };

        // 3. 持久化并返回 DTO
        await announcementRepository.AddAsync(announcement, cancellationToken);
        await announcementRepository.SaveChangesAsync(cancellationToken);

        return announcement.ToDto(false, null);
    }
}
