using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.PackageCQ.Commands.CreateNewPackage;
public class CreateNewPackageCommandHandler : IRequestHandler<CreateNewPackageCommand, CreateNewPackageResponseDto>
{
    private readonly IApplicationDbContext _context;

    public CreateNewPackageCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<CreateNewPackageResponseDto> Handle(CreateNewPackageCommand request,
        CancellationToken cancellationToken)
    {
        var entity = request.Adapt<Package>();
        await _context.Packages.AddAsync(entity, cancellationToken);
        entity.AddDomainEvent(new CreateNewPackageEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);

        // Sync PackageFeatures
        if (request.FeatureIds.Any())
        {
            foreach (var featureId in request.FeatureIds)
            {
                _context.PackageFeatures.Add(new PackageFeature
                {
                    PackageId = entity.Id,
                    ClubFeatureId = featureId,
                    IsIncluded = true
                });
            }
            await _context.SaveChangesAsync(cancellationToken);
        }

        return entity.Adapt<CreateNewPackageResponseDto>();
    }
}
