namespace Netina.Repository.Handlers.ProductCategories;

public class UpdateProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator,IMartenRepositoryWrapper martenRepositoryWrapper)
    : IRequestHandler<UpdateProductCategoryCommand, bool>
{
    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.FirstOrDefault(s => s.Id == dbFile.Id) == null)
            {
                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);
        await UpdateFaqAsync(newEnt, request.Faqs, cancellationToken);
        return true;
    }

    private async Task UpdateFaqAsync(ProductCategory 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.Name), cancellationToken);
        else
            await mediator.Send(new UpdateFaqCommand(newFaq.Id, faqs, url, newEnt.Name), cancellationToken);
    }
}