using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.PackageCQ.Commands.UpdatePackage;
public class UpdatePackageCommandHandler : IRequestHandler<UpdatePackageCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(UpdatePackageCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Packages
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(Package), request.Id);
        request.Adapt(entity);
        _context.Packages.Update(entity);
        entity.AddDomainEvent(new UpdatePackageEvent(entity));

        // Sync PackageFeatures — remove old, add new
        var existingFeatures = await _context.PackageFeatures
            .Where(pf => pf.PackageId == request.Id)
            .ToListAsync(cancellationToken);
        _context.PackageFeatures.RemoveRange(existingFeatures);

        foreach (var featureId in request.FeatureIds)
        {
            _context.PackageFeatures.Add(new PackageFeature
            {
                PackageId = request.Id,
                ClubFeatureId = featureId,
                IsIncluded = true
            });
        }

        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
