using Microsoft.EntityFrameworkCore;
using NetinaShop.Domain.Entities.ProductCategories;

namespace NetinaShop.Repository.Handlers.ProductCategories;

public class UpdateProductCategoryCommandHandler : IRequestHandler<UpdateProductCategoryCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public UpdateProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(UpdateProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<ProductCategory>().TableNoTracking
            .FirstOrDefaultAsync(c => c.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("ProductCategory not found", ApiResultStatusCode.NotFound);

        var newEnt = ProductCategory.Create(request.Name, request.Description, request.IsMain);
        newEnt.Id = ent.Id;
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;
        if (request.ParentId != default)
            newEnt.SetParent(request.ParentId);
        

        var dbFiles = await _repositoryWrapper.SetRepository<ProductCategoryStorageFile>().TableNoTracking
            .Where(s => s.CategoryId == newEnt.Id).ToListAsync(cancellationToken);
        foreach (var dbFile in dbFiles)
        {
            if (request.Files.Any(s => s.Id == dbFile.Id))
            {
                _repositoryWrapper.SetRepository<ProductCategoryStorageFile>().Delete(dbFile);
                await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }
        foreach (var file in request.Files.Where(f => f.Id == default))
        {
            newEnt.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
        }
        _repositoryWrapper.SetRepository<ProductCategory>().Update(newEnt);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}