using Netina.Domain.Entities.Brands;

namespace Netina.Repository.Handlers.Brands;

public class UpdateBrandCommandHandler(IRepositoryWrapper repositoryWrapper,IMartenRepositoryWrapper martenRepositoryWrapper,IMediator mediator) : IRequestHandler<UpdateBrandCommand, bool>
{
    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);
        await UpdateFaqAsync(newEnt, request.Faqs, cancellationToken);
        return true;
    }


    private async Task UpdateFaqAsync(Brand newEnt, Dictionary<string, string> faqs, CancellationToken cancellationToken)
    {
        var url = newEnt.GetWebSiteUrl();
        var oldFaq = await martenRepositoryWrapper.SetRepository<BaseFaq>()
            .GetEntityAsync(f => f.Slug == newEnt.Slug, cancellationToken);
        var newFaq = await martenRepositoryWrapper.SetRepository<BaseFaq>()
            .GetEntityAsync(f => f.Slug == url, cancellationToken);
        if (oldFaq != null)
            await mediator.Send(new DeleteFaqCommand(oldFaq.Id), cancellationToken);

        if (newFaq == null)
            await mediator.Send(new CreateFaqCommand(faqs, url, newEnt.EnglishName), cancellationToken);
        else
            await mediator.Send(new UpdateFaqCommand(newFaq.Id, faqs, url, newEnt.EnglishName), cancellationToken);
    }
}