using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;

namespace CMSMicroservice.Application.ProductsCQ.Commands.DeleteProducts;

public class DeleteProductsCommandHandler : IRequestHandler<DeleteProductsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(DeleteProductsCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Products
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken)
            ?? throw new NotFoundException(nameof(Product), request.Id);

        // Remove category associations
        var productCategories = await _context.ProductCategories
            .Where(pc => pc.ProductId == entity.Id)
            .ToListAsync(cancellationToken);
        _context.ProductCategories.RemoveRange(productCategories);

        // Remove gallery associations
        var productGalleries = await _context.ProductGalleries
            .Where(pg => pg.ProductId == entity.Id)
            .ToListAsync(cancellationToken);
        _context.ProductGalleries.RemoveRange(productGalleries);

        _context.Products.Remove(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
