using MediatR;
using TakeoutSaaS.Application.App.QuotaPackages.Commands;
using TakeoutSaaS.Application.App.QuotaPackages.Dto;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Ids;

namespace TakeoutSaaS.Application.App.QuotaPackages.Handlers;

/// <summary>
/// 创建配额包命令处理器。
/// </summary>
public sealed class CreateQuotaPackageCommandHandler(
    IQuotaPackageRepository quotaPackageRepository,
    IIdGenerator idGenerator)
    : IRequestHandler<CreateQuotaPackageCommand, QuotaPackageDto>
{
    /// <inheritdoc />
    public async Task<QuotaPackageDto> Handle(CreateQuotaPackageCommand request, CancellationToken cancellationToken)
    {
        // 1. 创建配额包实体
        var quotaPackage = new QuotaPackage
        {
            Id = idGenerator.NextId(),
            Name = request.Name,
            QuotaType = request.QuotaType,
            QuotaValue = request.QuotaValue,
            Price = request.Price,
            IsActive = request.IsActive,
            SortOrder = request.SortOrder,
            Description = request.Description,
            CreatedAt = DateTime.UtcNow
        };

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

        // 3. 返回 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
        };
    }
}
