using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.DiscountShop;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.AddDiscountProductImage;

public class AddDiscountProductImageCommandHandler : IRequestHandler<AddDiscountProductImageCommand, long>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<long> Handle(AddDiscountProductImageCommand request, CancellationToken cancellationToken)
    {
        // Verify product exists
        var productExists = await _context.DiscountProducts
            .AnyAsync(p => p.Id == request.DiscountProductId, cancellationToken);
        
        if (!productExists)
            throw new InvalidOperationException($"DiscountProduct with Id {request.DiscountProductId} not found.");

        // Get the max sort order for this product
        var maxSortOrder = await _context.DiscountProductImages
            .Where(i => i.DiscountProductId == request.DiscountProductId)
            .MaxAsync(i => (int?)i.SortOrder, cancellationToken) ?? 0;

        var image = new DiscountProductImage
        {
            DiscountProductId = request.DiscountProductId,
            ImagePath = request.ImagePath,
            ThumbnailPath = request.ThumbnailPath,
            Title = request.Title,
            AltText = request.AltText,
            SortOrder = maxSortOrder + 1,
            IsActive = true
        };

        _context.DiscountProductImages.Add(image);
        await _context.SaveChangesAsync(cancellationToken);

        return image.Id;
    }
}
