using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Brands;

namespace Netina.Repository.Handlers.Brands;

public class UpdateBrandCommandHandler : IRequestHandler<UpdateBrandCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public UpdateBrandCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(UpdateBrandCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<Brand>().TableNoTracking
            .FirstOrDefaultAsync(b => b.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Brand not found");
        var newEnt = Brand.Create(request.PersianName,request.EnglishName, request.Description, request.HasSpecialPage, request.PageUrl);
        newEnt.Id = ent.Id; 
        newEnt.CreatedAt = ent.CreatedAt;
        newEnt.CreatedBy = ent.CreatedBy;

        var dbFiles = await _repositoryWrapper.SetRepository<BrandStorageFile>().TableNoTracking
            .Where(s => s.BrandId == newEnt.Id).ToListAsync(cancellationToken);
        foreach (var dbFile in dbFiles)
        {
            if (request.Files.FirstOrDefault(s => s.Id == dbFile.Id) == null)
            {
                _repositoryWrapper.SetRepository<BrandStorageFile>().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<Brand>().Update(newEnt);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}