using MediatR;
using TakeoutSaaS.Application.App.QuotaPackages.Commands;
using TakeoutSaaS.Application.App.QuotaPackages.Dto;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.QuotaPackages.Handlers;

/// <summary>
/// 更新配额包命令处理器。
/// </summary>
public sealed class UpdateQuotaPackageCommandHandler(IQuotaPackageRepository quotaPackageRepository)
    : IRequestHandler<UpdateQuotaPackageCommand, QuotaPackageDto?>
{
    /// <inheritdoc />
    public async Task<QuotaPackageDto?> Handle(UpdateQuotaPackageCommand request, CancellationToken cancellationToken)
    {
        // 1. 查找配额包
        var quotaPackage = await quotaPackageRepository.FindByIdAsync(request.QuotaPackageId, cancellationToken);

        if (quotaPackage == null)
        {
            return null;
        }

        // 2. 更新配额包
        quotaPackage.Name = request.Name;
        quotaPackage.QuotaType = request.QuotaType;
        quotaPackage.QuotaValue = request.QuotaValue;
        quotaPackage.Price = request.Price;
        quotaPackage.IsActive = request.IsActive;
        quotaPackage.SortOrder = request.SortOrder;
        quotaPackage.Description = request.Description;
        quotaPackage.UpdatedAt = DateTime.UtcNow;

        // 3. 保存到数据库
        await quotaPackageRepository.UpdateAsync(quotaPackage, cancellationToken);
        await quotaPackageRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return new QuotaPackageDto
        {
            Id = quotaPackage.Id,
            Name = quotaPackage.Name,
            QuotaType = quotaPackage.QuotaType,
            QuotaValue = quotaPackage.QuotaValue,
            Price = quotaPackage.Price,
            IsActive = quotaPackage.IsActive,
            SortOrder = quotaPackage.SortOrder,
            Description = quotaPackage.Description,
            CreatedAt = quotaPackage.CreatedAt,
            UpdatedAt = quotaPackage.UpdatedAt
        };
    }
}
