using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateDiscountProductImage;

public class UpdateDiscountProductImageCommandHandler : IRequestHandler<UpdateDiscountProductImageCommand, bool>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<bool> Handle(UpdateDiscountProductImageCommand request, CancellationToken cancellationToken)
    {
        var image = await _context.DiscountProductImages
            .FirstOrDefaultAsync(i => i.Id == request.Id, cancellationToken);

        if (image == null)
            return false;

        image.ImagePath = request.ImagePath;
        image.ThumbnailPath = request.ThumbnailPath;
        image.Title = request.Title;
        image.AltText = request.AltText;
        image.IsActive = request.IsActive;

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}
